package com.icinfo.cloud.provider.punish.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.icinfo.cloud.common.security.util.UserUtil;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.constant.PunishMainServicePortUriConstant;
import com.icinfo.cloud.provider.common.enums.*;
import com.icinfo.cloud.provider.common.utils.*;
import com.icinfo.cloud.provider.exception.BusinessException;
import com.icinfo.cloud.provider.punish.actscode.dto.ActsCodeDto;
import com.icinfo.cloud.provider.punish.actscode.dto.ActsCodeRevokeDto;
import com.icinfo.cloud.provider.punish.api.dto.ApiSimpleCaseDetailInfoCallbackDto;
import com.icinfo.cloud.provider.punish.api.service.IApiSimpleCaseDetailInfoCallbackService;
import com.icinfo.cloud.provider.punish.app.enums.AppCaseConvertTemporaryEnum;
import com.icinfo.cloud.provider.punish.approval.vo.LineTerritoryInfoVo;
import com.icinfo.cloud.provider.punish.common.datareport.dto.CollectReportDataDto;
import com.icinfo.cloud.provider.punish.common.documentoperate.dto.FillAndConvertToPdfRequest;
import com.icinfo.cloud.provider.punish.common.documentoperate.dto.StageDocCommonOperateSaveDto;
import com.icinfo.cloud.provider.punish.common.publicsecurityentrust.dto.PublicSecurityDocumentNumberRollbackDTO;
import com.icinfo.cloud.provider.punish.common.seal.dto.FileSealInfoQueryDto;
import com.icinfo.cloud.provider.punish.config.dto.CompareSingleDiscretionDto;
import com.icinfo.cloud.provider.punish.config.dto.RelationWorkflowInfoRequest;
import com.icinfo.cloud.provider.punish.config.model.ConfigBusiParamDocumentInfo;
import com.icinfo.cloud.provider.punish.config.model.ConfigBusiParamMain;
import com.icinfo.cloud.provider.punish.config.model.SysDepartParam;
import com.icinfo.cloud.provider.punish.datareport.model.DataReportSaveFailRecordOfApp;
import com.icinfo.cloud.provider.punish.dto.*;
import com.icinfo.cloud.provider.punish.external.dto.EntBaseInfoDto;
import com.icinfo.cloud.provider.punish.mapper.*;
import com.icinfo.cloud.provider.punish.service.*;
import com.icinfo.cloud.provider.punish.simple.transfer.model.CaseSimpleTransferRecord;
import com.icinfo.cloud.provider.punish.ucase.casemain.dto.CaseDocumentRecordDto;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.PoliceAdjudicationVo;
import com.icinfo.cloud.provider.punish.ucase.caseregister.dto.CaseHandlePersonInfoDto;
import com.icinfo.cloud.provider.punish.ucase.caseregister.dto.RealNameCheckDto;
import com.icinfo.cloud.provider.punish.ucase.caseregister.enums.RealNameCheckResultEnum;
import com.icinfo.cloud.provider.punish.ucase.caseregister.vo.HandleAssistVo;
import com.icinfo.cloud.provider.punish.ucase.caseregister.vo.RealNameCheckVo;
import com.icinfo.cloud.provider.punish.ucase.payment.dto.CasePaymentSlipNumberSaveDto;
import com.icinfo.cloud.provider.punish.ucase.payment.enums.PayStatusEnum;
import com.icinfo.cloud.provider.punish.ucase.payment.enums.PayWayEnum;
import com.icinfo.cloud.provider.punish.ucase.payment.model.CasePaymentMainRecord;
import com.icinfo.cloud.provider.punish.ucase.payment.model.CasePaymentResultRecord;
import com.icinfo.cloud.provider.punish.ucase.payment.vo.CasePaymentResultRecordVo;
import com.icinfo.cloud.provider.punish.vo.*;
import com.icinfo.cloud.xzcf.provider.member.userinfo.dto.UserDTO;
import com.icinfo.framework.common.web.Result;
import com.icinfo.framework.mybatis.mapper.entity.Example;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description 简易处罚对应的Service接口实现类
 * @Author zhengqiang
 * @Date 2022/6/14 14:30
 **/
@Slf4j
@Service
public class SimpleCaseServiceImpl implements ISimpleCaseService {

    @Resource
    private CaseMainDetailSimpleInfoMapper caseMainDetailSimpleInfoMapper;
    @Resource
    private CaseMainInfoMapper caseMainInfoMapper;
    @Resource
    private CaseReasonMainRecordMapper caseReasonMainRecordMapper;
    @Resource
    private CaseHandlePersonRecordMapper caseHandlePersonRecordMapper;
    @Resource
    private IAppCaseBeforeDocumentRecordService appCaseBeforeDocumentRecordService;
    @Resource
    private IDocumentSendRecordService documentSendRecordService;
    @Resource
    private CasePartiesRecordMapper casePartiesRecordMapper;
    @Resource
    private CasePartiesPersonInfoMapper casePartiesPersonInfoMapper;
    @Resource
    private CasePartiesLegalInfoMapper casePartiesLegalInfoMapper;
    @Resource
    private CaseAppendixRecordMapper caseAppendixRecordMapper;
    @Resource
    private ConfigBusiParamDocumentInfoMapper configBusiParamDocumentInfoMapper;

    @Resource
    private CaseTemporaryRecordMapper caseTemporaryRecordMapper;
    @Resource
    private ICaseMainDetailSimpleInfoService caseMainDetailSimpleInfoService;
    @Resource
    private SysDepartParamMapper sysDepartParamMapper;
    @Resource
    private IConfigBusiParamMainService configBusiParamMainService;
    @Resource
    private CaseDocumentRecordMapper caseDocumentRecordMapper;
    @Resource
    private IXzzfInterfaceService xzzfInterfaceService;
    @Resource
    private ISysDepartParamService sysDepartParamService;
    @Resource
    private IApiSimpleCaseDetailInfoCallbackService iApiSimpleCaseDetailInfoCallbackService;
    @Resource
    private ICaseMainInfoService caseMainInfoService;
    @Resource
    private ISimpleCaseApiService simpleCaseApiService;
    @Resource
    private IConfigBusiParamDocumentInfoService configBusiParamDocumentInfoService;
    @Resource
    private CasePaymentResultRecordMapper casePaymentResultRecordMapper;
    @Value("${isCheckHandleSign}")
    private String isCheckHandleSign;
    @Value("${tzService.url}")
    private String url;
    @Resource
    private CaseMainDetailAuxiliaryInfoMapper caseMainDetailAuxiliaryInfoMapper;
    @Resource
    private CasePaymentMainRecordMapper casePaymentMainRecordMapper;
    @Resource
    private ICaseDocumentRecordService caseDocumentRecordService;
    @Resource
    private DataReportSaveFailRecordMapper dataReportSaveFailRecordMapper;
    @Resource
    private ICaseReasonMainRecordService caseReasonMainRecordService;

    @Value("${paymentCq.busInvalidUnpayDataUrl}")
    private String busInvalidUnpayDataUrl;

    @Resource
    private ICaseSimpleTransferRecordService caseSimpleTransferRecordService;

    @Resource
    private IAppCaseConvertTemporaryRecordService appCaseConvertTemporaryRecordService;


    /**
     * 根据案由编码及当事人id查询1年内重复违法次数
     *
     * @return {@link int}
     * @author: zhengqiang
     * @date: 2022/6/16
     * @param: queryDto
     **/
    @Override
    public int getCaseMainCountByReasonCodeAndParty(CaseReasonQueryDto queryDto) {
        return caseReasonMainRecordMapper.selectCaseMainCountByReasonCodeAndParty(queryDto);
    }

    /**
     * 根据案由编码及当事人查询1年内违法列表
     *
     * @return {@link int}
     * @author: zhengqiang
     * @date: 2022/6/16
     * @param: queryDto
     **/
    @Override
    public CaseMainQueryByYearVo getCaseMainListByReasonCodeAndParty(CaseReasonQueryDto queryDto) {
        CaseMainQueryByYearVo vo = new CaseMainQueryByYearVo();
        //根据案由编码及当事人查询1年内重复违法列表
        List<CaseMainRepeatVo> partyReasonCaseList = caseReasonMainRecordMapper.selectCaseMainListByReasonCodeAndParty(queryDto);
        //根据当事人查询1年内违法列表
        List<CaseMainRepeatVo> partyCaseList = caseReasonMainRecordMapper.selectCaseMainListByParty(queryDto);
        vo.setPartyReasonCaseList(partyReasonCaseList);
        vo.setPartyCaseList(partyCaseList);
        return vo;
    }

    /**
     * 根据案由编码及当事人查询2年内，重复违法，全部违法，责令改正
     *
     * @param queryDto
     * @return
     */
    @Override
    public CasePartyIllegalTimesVo getIllegalTimesByReasonCodeAndParty(CaseReasonQueryDto queryDto) {
        if (queryDto.getCountYear() == null || queryDto.getCountYear() < Constant.INTEGER_1) {
            queryDto.setCountYear(Constant.INTEGER_1);
        }
        queryDto.setCountYearParam(queryDto.getCountYear() + " year");
        CasePartyIllegalTimesVo vo = new CasePartyIllegalTimesVo();
        //根据案由编码及当事人查询2年内重复违法列表
        List<CaseMainRepeatVo> partyReasonCaseList = caseReasonMainRecordMapper.selectIllegalTimesByReasonCodeAndParty(queryDto);
        vo.setPartyReasonCaseList(partyReasonCaseList);
        //根据当事人查询2年内全部违法列表
        List<CaseMainRepeatVo> partyCaseList = caseReasonMainRecordMapper.selectIllegalTimesByParty(queryDto);
        vo.setPartyCaseList(partyCaseList);
        //获取责令改正列表
        List<CaseMainRepeatVo> partyOrderCorrectionList = caseReasonMainRecordMapper.selectOrderCorrectionTimesByParty(queryDto);
        vo.setPartyOrderCorrectionList(partyOrderCorrectionList);
        return vo;
    }

    /**
     * 根据案由编码及当事人获取N年内重复违法次数（立案通过即算）
     *
     * @param: queryDto
     **/
    @Override
    public int getIllegalTimesCountByReasonCodeAndParty(CaseReasonQueryDto queryDto) {
        if (queryDto.getCountYear() == null || queryDto.getCountYear() < Constant.INTEGER_1) {
            queryDto.setCountYear(Constant.INTEGER_1);
        }
        queryDto.setCountYearParam(queryDto.getCountYear() + " year");
        return caseReasonMainRecordMapper.getIllegalTimesCountByReasonCodeAndParty(queryDto);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public SimpleCaseSaveVo saveCase(SimpleCaseSaveDto saveDto) {
        System.out.println("saveCase参数:" + JSONObject.toJSONString(saveDto));
        //案件状态校验
        checkCaseStatus(saveDto);

        SimpleCaseSaveVo saveVo = new SimpleCaseSaveVo();
        // 校验简易处罚数据
        String errorMsg = checkSimpleCase(saveDto);
        if (StringUtils.isNotEmpty(errorMsg)) {
            throw new BusinessException(errorMsg);
        }
        UserDTO userInfo = UserUtil.getUserInfo();

        //1、处理简易处罚-主表、宽表信息
        dealCaseMainInfo(saveDto, userInfo);
        //2、处理案由信息
        dealCaseReasonInfo(saveDto);
        //3、处理办案人员信息
        dealCaseHandlePersonInfo(saveDto, userInfo);
        //4、处理当事人信息
        dealCasePartiesInfo(saveDto);

        //不予处罚时,直接结案
        if (Constant.STRING_2.equals(saveDto.getInvestConclusion())) {
            SimpleCaseSaveFinishDto simpleCaseSaveFinishDto = new SimpleCaseSaveFinishDto();
            simpleCaseSaveFinishDto.setCaseId(saveDto.getCaseId());
            simpleCaseSaveFinishDto.setInvestConclusion(saveDto.getInvestConclusion());
            saveCaseFinish(simpleCaseSaveFinishDto);
        } else {
            //保存暂存数据
            saveDto.setIsAutoSave(YesOrNoEnum.NO.getCode());
            saveTemporary(saveDto);
        }

        saveVo.setCaseId(saveDto.getCaseId());
        return saveVo;
    }

    /**
     * 案件状态校验
     *
     * @param saveDto
     */
    private void checkCaseStatus(SimpleCaseSaveDto saveDto) {
        if (ObjectUtils.isEmpty(saveDto.getCaseId())) {
            return;
        }
        CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(saveDto.getCaseId());
        String caseStatus = caseMainInfo.getCaseStatus();
        if (!ObjectUtils.isEmpty(caseMainInfo) && CaseStatusEnum.END_CASE.getCode().equals(caseStatus)) {
            throw new BusinessException("案件结案状态时无法进行此操作");
        }
        if (CaseStatusEnum.PUNISH_REVOKE.getCode().equals(caseStatus)) {
            throw new BusinessException("案件已撤销");
        }
        //查看用户是否缴款，已缴款不可撤销
        CasePaymentResultRecordVo casePaymentResultRecordVo = getCasePaymentResultRecordDetailByCaseId(saveDto.getCaseId());
        if (ObjectUtil.isNotEmpty(casePaymentResultRecordVo)) {
            throw new BusinessException("案件的处罚已缴款");
        }
    }

    /**
     * 删除当前用户异常暂存数据
     *
     * @param saveDto
     */
    @Override
    public void dealTemporaryCaseData(SimpleCaseSaveDto saveDto) {
        if (ObjectUtils.isEmpty(saveDto.getCaseId())) {
            simpleCaseApiService.dealTemporaryCaseData();
        }
    }

    @Override
    public List<SimpleCaseRepeatInfoVo> getSimpleCaseRepeatList(SimpleCaseRepeatQueryDto queryDto) {
        //日期转换
        String longDate = "";
        try {
            Date format1 = new SimpleDateFormat("yyyy-M-d").parse(queryDto.getCaseHappenTime());
            longDate = new SimpleDateFormat("yyyy-MM-dd").format(format1);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        queryDto.setCaseHappenTime(longDate);
        return caseMainDetailSimpleInfoMapper.selectSimpleCaseRepeatList(queryDto);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveSimpleCaseRecall(SimpleCaseRecallSaveDto saveDto) {
        UserDTO userInfo = UserUtil.getUserInfo();
        if (userInfo == null) {
            throw new com.icinfo.cloud.provider.common.exception.BusinessException("请先登录!");
        }
        String caseId = saveDto.getCaseId();
        LocalDateTime now = LocalDateTime.now();
        CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(caseId);
        //校验案件是否可以撤销
        checkSimpleCaseRecall(caseId, caseMainInfo);
        //更新简易程序详情
        Example example = new Example(CaseMainDetailSimpleInfo.class);
        example.createCriteria().andEqualTo("caseId", caseId);
        CaseMainDetailSimpleInfo simpleInfo = new CaseMainDetailSimpleInfo();
        simpleInfo.setRecallReasonCode(saveDto.getRecallReasonCode());
        simpleInfo.setRecallReasonDesc(saveDto.getRecallReasonDesc());
        simpleInfo.setUpdateTime(now);
        caseMainDetailSimpleInfoMapper.updateByExampleSelective(simpleInfo, example);
        ////无效缴款信息
        Example query = new Example(CasePaymentMainRecord.class);
        query.createCriteria().andEqualTo("caseId", caseId).andIsNull("status");
        List<CasePaymentMainRecord> casePaymentMainRecords = casePaymentMainRecordMapper.selectByExample(query);
        if (!ObjectUtils.isEmpty(casePaymentMainRecords)) {
            CasePaymentMainRecord casePaymentMainRecord = casePaymentMainRecords.get(0);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("docNumber", casePaymentMainRecord.getNoticeNo());
            jsonObject.put("deptId", casePaymentMainRecord.getEnterCode());
            HttpUtils.doPostJson(busInvalidUnpayDataUrl, jsonObject.toJSONString());
        }
        //更新缴款单状态为已失效
        Example updateE = new Example(CasePaymentMainRecord.class);
        updateE.createCriteria().andEqualTo("caseId", caseId);
        CasePaymentMainRecord mainRecord = new CasePaymentMainRecord();
        mainRecord.setStatus(PayStatusEnum.INVALID.getCode());
        casePaymentMainRecordMapper.updateByExampleSelective(mainRecord, updateE);

        //1、更新主表信息
        CaseMainInfo updateCaseMainInfo = new CaseMainInfo();
        updateCaseMainInfo.setId(caseId);
        updateCaseMainInfo.setCaseStatus(CaseStatusEnum.SIMPLE_CASE_REVOKE.getCode());
        int count = caseMainInfoMapper.updateByPrimaryKeySelective(updateCaseMainInfo);
        if (count > 0) {
            return true;
        }
        return false;
    }

    /**
     * 描述：校验撤销案件参数
     *
     * @param caseId       用例id
     * @param caseMainInfo 案例主要信息
     * @author shishengyao
     * @date 2022/11/24
     */
    private void checkSimpleCaseRecall(String caseId, CaseMainInfo caseMainInfo) {
        if (ObjectUtil.isEmpty(caseMainInfo)) {
            throw new BusinessException("案件不存在");
        }
        String caseStatus = caseMainInfo.getCaseStatus();
        if (CaseStatusEnum.END_CASE.getCode().equals(caseStatus)) {
            throw new BusinessException("案件已结案");
        }
        if (CaseStatusEnum.PUNISH_REVOKE.getCode().equals(caseStatus)) {
            throw new BusinessException("案件已撤销");
        }
        //查看用户是否缴款，已缴款不可撤销
        CasePaymentResultRecordVo casePaymentResultRecordVo = getCasePaymentResultRecordDetailByCaseId(caseId);
        if (ObjectUtil.isNotEmpty(casePaymentResultRecordVo)) {
            throw new BusinessException("处罚已缴款");
        }
    }

    /**
     * 【V1.1.0】描述：根据案件id查询最新缴款结果信息
     *
     * @param caseId 案件id
     * @return {@link CasePaymentResultRecordVo} 案件缴款结果记录详情
     * @author xiangyuyu
     * @date 2022-04-25 15:34
     */
    public CasePaymentResultRecordVo getCasePaymentResultRecordDetailByCaseId(String caseId) {
        Example e = new Example(CasePaymentResultRecord.class);
        e.createCriteria().andEqualTo("caseId", caseId).andEqualTo("isDelete", YesOrNoEnum.NO.getCode());
        e.setOrderByClause("create_time desc");
        List<CasePaymentResultRecord> list = casePaymentResultRecordMapper.selectByExample(e);
        if (ObjectUtils.isEmpty(list) || list.size() == 0) {
            return null;
        }
        CasePaymentResultRecord record = list.get(Constant.INTEGER_0);
        CasePaymentResultRecordVo vo = new CasePaymentResultRecordVo();
        BeanUtils.copyProperties(record, vo);
        return vo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveSimpleCaseExecuteFinish(SimpleCaseExecuteFinishSaveDto saveDto) {
        if (caseReasonMainRecordService.getIsContainPublicSecurityByCaseId(saveDto.getCaseId())) {
            throw new BusinessException("简易程序公安委托执法案件无该操作");
        }
        //保存附件
        UserDTO userInfo = UserUtil.getUserInfo();
        if (userInfo == null) {
            throw new com.icinfo.cloud.provider.common.exception.BusinessException("请先登录!");
        }
        String caseId = saveDto.getCaseId();
        CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(caseId);
        if (CaseStatusEnum.END_CASE.getCode().equals(caseMainInfo.getCaseStatus())) {
            throw new BusinessException("案件已结案，不可再执行完毕");
        }
        //保存附件
        List<CaseAppendixSaveDto> appendixSaveDtoList = saveDto.getAppendixSaveDtoList();
        appendixSaveDtoList.forEach(e -> {
            saveAppendix(e, caseId, userInfo);
        });

        //更新简易案件详情表
        updateCaseMainDetailSimploeInfo(saveDto);

        //执行成功更新缴款单状态为线下已缴款
        updatePaymentStatus(caseId);
        //结案
        return endCase(caseId) > 0;
    }

    /**
     * 结案
     */
    private int endCase(String caseId) {
        CaseMainInfo updateCaseMainInfo = new CaseMainInfo();
        LocalDateTime now = LocalDateTime.now();
        updateCaseMainInfo.setId(caseId);
        updateCaseMainInfo.setCaseStatus(CaseStatusEnum.END_CASE.getCode());
        updateCaseMainInfo.setCaseEndTime(now);
        //阶段编码默认写死（台州工作流）
        updateCaseMainInfo.setCaseCurrentStageCode("CLOSE_ARCHIVING");
        updateCaseMainInfo.setCaseCurrentStageName("结案");
        updateCaseMainInfo.setCaseCurrentLinkCode("LINK-202203020953");
        updateCaseMainInfo.setCaseCurrentLinkName("归档");
        int count = caseMainInfoMapper.updateByPrimaryKeySelective(updateCaseMainInfo);
        return count;
    }

    /**
     * 更新缴款单状态为线下已缴款
     *
     * @param caseId
     */
    private void updatePaymentStatus(String caseId) {
        Example updateE = new Example(CasePaymentMainRecord.class);
        updateE.createCriteria().andEqualTo("caseId", caseId);
        CasePaymentMainRecord mainRecord = new CasePaymentMainRecord();
        mainRecord.setStatus(PayStatusEnum.OFFLINE_PAID.getCode());
        casePaymentMainRecordMapper.updateByExampleSelective(mainRecord, updateE);
    }

    /**
     * 更新简易案件详情表
     *
     * @param saveDto
     */
    private void updateCaseMainDetailSimploeInfo(SimpleCaseExecuteFinishSaveDto saveDto) {
        CaseMainDetailSimpleInfo caseMainDetailSimpleInfo = caseMainDetailSimpleInfoService.getCaseMainDetailSimpleInfo(saveDto.getCaseId());
        CaseMainDetailSimpleInfo updateInfo = new CaseMainDetailSimpleInfo();
        updateInfo.setId(caseMainDetailSimpleInfo.getId());
        updateInfo.setExecuteWay(saveDto.getExecuteWay());
        updateInfo.setExecuteFinishDate(saveDto.getExecuteFinishDate());
        updateInfo.setExecuteConditionDesc(saveDto.getExecuteConditionDesc());
        caseMainDetailSimpleInfoMapper.updateByPrimaryKeySelective(updateInfo);
    }

    /**
     * 保存附件
     */
    private void saveAppendix(CaseAppendixSaveDto e, String caseId, UserDTO userInfo) {
        CustomCheckParamUtil.doCheck(e);
        CaseAppendixRecord appendixRecord = new CaseAppendixRecord();
        String attachmentId = e.getId();
        appendixRecord.setCaseId(caseId);
        if (ObjectUtils.isEmpty(attachmentId)) {
            BeanUtils.copyProperties(e, appendixRecord);
            appendixRecord.setId(BaseUtil.createUid());
            appendixRecord.setDocumentCatalogCode("");
            if (!ObjectUtils.isEmpty(userInfo)) {
                appendixRecord.setUploadUserId(userInfo.getUserId() + "");
                appendixRecord.setUploadUserName(userInfo.getRealName());
            }
            appendixRecord.setUploadTime(LocalDateTime.now());
            appendixRecord.setAppendixUrl(e.getAppendixUrl());
            appendixRecord.setAppendixName(e.getAppendixName());
            appendixRecord.setIsDelete(Constant.STRING_0);
            String appendixTypeId = AttachmentTypeEnum.SIMPLE_CASE_ATTACHMENT_01.getCode();
            appendixRecord.setAppendixTypeId(appendixTypeId);
            caseAppendixRecordMapper.insertSelective(appendixRecord);
        }
    }

    /**
     * 删除当前用户暂存数据
     *
     * @return
     */
    @Override
    public boolean deleteTemporaryCase() {
        UserDTO userInfo = UserUtil.getUserInfo();
        Example delExample = new Example(CaseTemporaryRecord.class);
        delExample.createCriteria().andEqualTo("addUser", userInfo.getLoginName())
                .andEqualTo("caseId", "EMPTY").andEqualTo("orgCode", userInfo.getOrgCode());
        int count = caseTemporaryRecordMapper.deleteByExample(delExample);
        if (count > 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 描述： 删除简易处罚案件相关信息
     *
     * @return {@link boolean}
     * @author: zhengqiang
     * @date: 2022/6/24
     * @param: caseId
     **/
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteCaseInfo(String caseId) {
        CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(caseId);

        //设置暂存数据内容中caseId为空
        UserDTO userInfo = UserUtil.getUserInfo();
        //查询是否存在暂存记录
        Example queryExample = new Example(CaseTemporaryRecord.class);
        queryExample.createCriteria().andEqualTo("addUser", userInfo.getLoginName())
                .andEqualTo("caseId", "EMPTY").andEqualTo("orgCode", userInfo.getOrgCode());
        List<CaseTemporaryRecord> caseTemporaryRecords = caseTemporaryRecordMapper.selectByExample(queryExample);
        if (!ObjectUtils.isEmpty(caseTemporaryRecords)) {
            CaseTemporaryRecord caseTemporaryRecord = caseTemporaryRecords.get(0);
            SimpleCaseInfoVo vo = JSONObject.parseObject(caseTemporaryRecord.getContent(), SimpleCaseInfoVo.class);
            vo.setCaseId(null);
            CaseTemporaryRecord record = new CaseTemporaryRecord();
            record.setContent(JSONObject.toJSONString(vo));
            caseTemporaryRecordMapper.updateByExampleSelective(record, queryExample);
        }

        if (caseMainInfo == null) {
            return true;
        }
        //1.删除简易处罚详情表信息
        Example simpleExample = new Example(CaseMainDetailSimpleInfo.class);
        simpleExample.createCriteria().andEqualTo("caseId", caseId);
        caseMainDetailSimpleInfoMapper.deleteByExample(simpleExample);

        //2.删除当事人相关表信息
        Example partyExample = new Example(CasePartiesRecord.class);
        partyExample.createCriteria().andEqualTo("caseId", caseId).andEqualTo("status", Constant.STRING_1);
        List<CasePartiesRecord> casePartiesRecords = casePartiesRecordMapper.selectByExample(partyExample);
        for (int i = 0; i < casePartiesRecords.size(); i++) {
            if (PartyTypeEnum.PERSON.getCode().equals(casePartiesRecords.get(i).getPartyType())) {
                casePartiesPersonInfoMapper.deleteByPrimaryKey(casePartiesRecords.get(i).getPartyId());
            } else if (PartyTypeEnum.LEGAL.getCode().equals(casePartiesRecords.get(i).getPartyType())) {
                casePartiesLegalInfoMapper.deleteByPrimaryKey(casePartiesRecords.get(i).getPartyId());
            }
        }
        casePartiesRecordMapper.deleteByExample(partyExample);

        //3.删除办案人员表--2个
        Example handleExample = new Example(CaseHandlePersonRecord.class);
        handleExample.createCriteria().andEqualTo("caseId", caseId);
        caseHandlePersonRecordMapper.deleteByExample(handleExample);
        //4.添加附件表
        Example appendixRecordExample = new Example(CaseAppendixRecord.class);
        appendixRecordExample.createCriteria().andEqualTo("caseId", caseId);
        caseAppendixRecordMapper.deleteByExample(appendixRecordExample);
        //5.删除案由表
        Example reasonExample = new Example(CaseReasonMainRecord.class);
        reasonExample.createCriteria().andEqualTo("caseId", caseId);
        caseReasonMainRecordMapper.deleteByExample(reasonExample);
        //6.删除文书记录
        Example docExample = new Example(CaseDocumentRecord.class);
        docExample.createCriteria().andEqualTo("caseId", caseId);
        caseDocumentRecordMapper.deleteByExample(docExample);
        //7.删除主表
        caseMainInfoMapper.deleteByPrimaryKey(caseId);

        return true;
    }


    /**
     * 5.生成简易处罚相关文书
     *
     * @param saveDto
     * @param asyncKindList 异步处理文书种类
     */
    @Override
    public void dealSimpleCaseDocumentRecords(SimpleCaseSaveDto saveDto, List<String> asyncKindList) {
        UserDTO userInfo = UserUtil.getUserInfo();
        //简易程序文书种类列表
        List<String> simpleCaseDocs = getSimpleCaseDocs(saveDto);
        //获取领域下业务参数Id
        CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(saveDto.getCaseId());
        RelationWorkflowInfoRequest request = new RelationWorkflowInfoRequest();
        request.setApplyAreaCode(userInfo.getAreaCode());
        String applyFieldCode = caseMainInfo.getCaseTerritoryCode();
        request.setApplyFieldCode(applyFieldCode);

        if ("A037".equals(applyFieldCode)) {
            request.setApplyAreaCode(null);
        }
        // 判断是否是委托事项
        if ("4".equals(saveDto.getSxType())) {
            //将对象中的案件区划编码替换到request中
            request.setApplyAreaCode(caseMainInfo.getCaseAreaCode());
        }
        List<ConfigBusiParamMain> configBusiParamMainList = configBusiParamMainService.getConfigBusiParamMainList(request);
        String busiParamId = configBusiParamMainList.get(0).getId();

        Example example = new Example(ConfigBusiParamDocumentInfo.class);
        example.createCriteria().andEqualTo("busiParamId", busiParamId)
                .andIn("documentKindCode", simpleCaseDocs);
        List<ConfigBusiParamDocumentInfo> configBusiDocumentMainList = configBusiParamDocumentInfoMapper.selectByExample(example);
        String caseId = saveDto.getCaseId();
        for (ConfigBusiParamDocumentInfo config : configBusiDocumentMainList) {
            //根据配置组装文书生成参数
            StageDocCommonOperateSaveDto commonOperateSaveDto = assemblyCommonOperateDocumentDto(saveDto, config,
                    caseId, applyFieldCode, caseMainInfo, userInfo);
            log.info("----------进入文书生成公共服务saveDocInfo--------------");
            Result result = PunishMainClientUtil.httpPost(PunishMainServicePortUriConstant.SAVE_DOC_INFO, commonOperateSaveDto);
            if (result.getCode() != Result.DEFAULT_SUCCESS) {
                log.info("----------文书生成公共服务saveDocInfo------报错---");
                throw new BusinessException(result.getMessage());
            }
        }
        // 文书执行完毕，执行一次临时数据删除
        if (AppCaseConvertTemporaryEnum.SIMPLE_CONVERT.equals(saveDto.getConvertFlag())) {
            appCaseConvertTemporaryRecordService.removeCurrentUserConvertTemporaryRecord(saveDto.getConvertFlag());
        }
    }

    /**
     * 根据是否公安委托执法来获取对应的文书kindCode
     * @param saveDto
     * @return
     */
    private List<String> getSimpleCaseDocs(SimpleCaseSaveDto saveDto) {
        if (StrUtil.equals(saveDto.getSxType(), "4") && StrUtil.equals(saveDto.getIsPublicSecurity(), "1")) {
            // 如果是公安委托执法 则生成公安委托执法对应的文书
            return Arrays.asList(DocumentKindEnum.DOC_KIND_JYCXGAWTCFJDS.getCode(), DocumentKindEnum.DOC_KIND_XCZPJSM.getCode());
        }
        return Arrays.asList(DocumentKindEnum.DOC_KIND_JYCXCFJDS.getCode(), DocumentKindEnum.DOC_KIND_XCZPJSM.getCode());
    }


    /**
     * 根据配置组装文书生成参数
     *
     * @param saveDto
     * @param config         文书配置
     * @param caseId         案件id
     * @param applyFieldCode 领域编码
     * @param caseMainInfo   案件信息
     * @param userInfo       登录用户信息
     * @return
     */
    private StageDocCommonOperateSaveDto assemblyCommonOperateDocumentDto(SimpleCaseSaveDto saveDto,
                                                                          ConfigBusiParamDocumentInfo config,
                                                                          String caseId,
                                                                          String applyFieldCode,
                                                                          CaseMainInfo caseMainInfo,
                                                                          UserDTO userInfo) {
        StageDocCommonOperateSaveDto commonOperateSaveDto = new StageDocCommonOperateSaveDto();
        commonOperateSaveDto.setCaseId(caseId);
        commonOperateSaveDto.setDocumentCatalogCode(config.getDocumentCatalogCode());
        commonOperateSaveDto.setIsUpdateRelationTable(Constant.STRING_0);
        commonOperateSaveDto.setPartyId(saveDto.getPartyId());
        //设置文书参数
        commonOperateSaveDto.setDataMap(getDocumentDataMap(saveDto, config, applyFieldCode, caseMainInfo, userInfo));
        if (StrUtil.equals(DocumentKindEnum.DOC_KIND_JYCXGAWTCFJDS.getCode(), config.getDocumentKindCode())) {
            // 标记公安委托执法为窄幅文书
            commonOperateSaveDto.setDocumentTemplateType(Constant.STRING_2);
        }

        return commonOperateSaveDto;
    }

    /**
     * 获取文书内容参数
     *
     * @param saveDto
     * @param config         文书配置
     * @param applyFieldCode 领域code
     * @param caseMainInfo   案件信息
     * @param userInfo       用户信息
     * @return
     */
    private HashMap<String, Object> getDocumentDataMap(SimpleCaseSaveDto saveDto, ConfigBusiParamDocumentInfo config, String applyFieldCode, CaseMainInfo caseMainInfo, UserDTO userInfo) {
        saveDto.setOrgStandardName(documentSendRecordService.getStandOrgName());
        HashMap<String, Object> hashMap = BaseUtil.javaToMap(saveDto);
        if (ObjectUtils.isEmpty(saveDto.getSignFingerprintDate())) {
            hashMap.remove("signFingerprintDate");
        }
        if (ObjectUtils.isEmpty(saveDto.getSignFingerprintPic())) {
            hashMap.remove("signFingerprintPic");
        }
        //当事人信息处理
        dealDocumentPartInfo(saveDto, hashMap);
        //处理特殊领域参数
        dealSpecialApplyFieldCodeParams(saveDto, applyFieldCode, caseMainInfo, hashMap);
        //根据文书种类选择不同的参数组合策略
        documentKindParamsStrategy(saveDto, config, userInfo, hashMap);
        //处理扩展信息参数
        dealExtractJsonParams(saveDto, hashMap);
        return hashMap;
    }

    /**
     * 处理特殊领域文书参数
     *
     * @param saveDto
     * @param applyFieldCode 领域编码
     * @param caseMainInfo
     * @param hashMap
     */
    private void dealSpecialApplyFieldCodeParams(SimpleCaseSaveDto saveDto, String applyFieldCode, CaseMainInfo caseMainInfo, HashMap<String, Object> hashMap) {
        if ("A037".equals(applyFieldCode)) {
            dealA037CodeParams(saveDto, caseMainInfo, hashMap);
        }
    }

    /**
     * 处理A037特殊领域文书参数
     *
     * @param saveDto      简易程序保存参数
     * @param caseMainInfo 案件信息
     * @param hashMap      文书参数对象
     */
    private void dealA037CodeParams(SimpleCaseSaveDto saveDto, CaseMainInfo caseMainInfo, HashMap<String, Object> hashMap) {
        String orgCode = caseMainInfo.getCaseOrgCode();
        String deptCode = caseMainInfo.getCaseDeptCode();
        SysDepartParam sysDepartParam = sysDepartParamService.getSysDepartParamByOrgCode(orgCode, deptCode);
        String payBankName = sysDepartParam.getPayBankName();
        hashMap.put("payBankName", payBankName);

        //当事人证件类型
        String certType = saveDto.getCertType();
        if (!ObjectUtils.isEmpty(certType)) {
            String certTypeName = CertTypeEnum.getValueByCode(certType);
            hashMap.put("certType", certTypeName);
        }
    }

    /**
     * 文书种类参数组合策略
     *
     * @param saveDto  简易程序保存参数
     * @param config   文书配置
     * @param userInfo 用户信息
     * @param hashMap  文书参数
     */
    private void documentKindParamsStrategy(SimpleCaseSaveDto saveDto, ConfigBusiParamDocumentInfo config, UserDTO userInfo, HashMap<String, Object> hashMap) {
        //获取案发日期
        String happenTimeStr = getHappenTimeStr(saveDto.getCaseHappenTime(), "yyyy年M月d日");
        DocumentKindEnum documentKind = DocumentKindEnum.parseByCode(config.getDocumentKindCode());
        switch (documentKind) {
            case DOC_KIND_XCZPJSM:
                //现场照片及说明
                dealXczpjsmDocumentParams(saveDto, hashMap, userInfo, happenTimeStr);
                return;
            case DOC_KIND_JYCXCFJDS:
                //简易程序处罚决定书
                dealJycxcfjdsDocumentParams(saveDto, hashMap, userInfo);
                return;
            case DOC_KIND_JYCXGAWTCFJDS:
                dealJycxgawtcfjdsDocumentParams(saveDto, hashMap, userInfo);
                return;
            default:
        }
    }

    /**
     * 处理简易程序公安委托执法决定书
     *
     * @param saveDto
     * @param hashMap
     * @param userInfo
     */
    private void dealJycxgawtcfjdsDocumentParams(SimpleCaseSaveDto saveDto, HashMap hashMap, UserDTO userInfo) {
        String orgStandardName = StrUtil.isBlank(saveDto.getClientDeptName()) ? saveDto.getClientOrgName() : saveDto.getClientDeptName();
        String deptCode = StrUtil.isBlank(saveDto.getClientDeptCode()) ? saveDto.getClientOrgCode() : saveDto.getClientDeptCode();
        //部门名称
        hashMap.put("orgStandardName", orgStandardName);
        //身份证类型处理
        handleCertType(saveDto, hashMap);
        //处理违法信息：案发时间 违法地点  违法行为  违法代码
        handleIllegalInformation(saveDto, hashMap);
        //记分依据以及记分情况
        handleScoringBasis(saveDto, hashMap);
        //处罚项
        handlePunishDesc(saveDto, hashMap);
        // 签章
        handleDepartParam(saveDto, hashMap, deptCode);
        // 车牌
        hashMap.put("carPlateNumber", saveDto.getLicensePlateProvince() + saveDto.getLicensePlateNumber());
        //处理机构信息&机构文书抬头标准名称
        dealJg(saveDto, hashMap, userInfo);

    }

    /**
     * 将公安委托执法的记分相关信息填入
     * @param saveDto
     * @param hashMap
     */
    private void handleScoringBasis(SimpleCaseSaveDto saveDto, HashMap hashMap) {
        hashMap.put("jf", StrUtil.isBlank(saveDto.getLicenseScore()) ? "/" : saveDto.getLicenseScore());
        hashMap.put("scoringBasis", StrUtil.isBlank(saveDto.getScoringBasis()) ? "/" : saveDto.getScoringBasis());
    }

    /**
     * 根据处罚类型 填入对应的处罚详情
     * @param saveDto
     * @param hashMap
     */
    private void handlePunishDesc(SimpleCaseSaveDto saveDto, HashMap hashMap) {
        String punishDesc = saveDto.getDraftPunishMoney() + "元罚款";
        if (saveDto.getPunishKinds().contains("警告") && saveDto.getPunishKinds().contains("罚款")) {
            punishDesc = "警告;" + punishDesc;
        } else if ("警告".equals(saveDto.getPunishKinds())) {
            punishDesc = "警告";
        }
        hashMap.put("cfjd", punishDesc);
    }

    /**
     * 填充公安委托的签章信息
     * @param saveDto
     * @param hashMap
     * @param deptCode
     */
    private void handleDepartParam(SimpleCaseSaveDto saveDto, HashMap hashMap, String deptCode) {
        SysDepartParam sysDepartParam = sysDepartParamService.getPublicSecurityEntrustSysDepartParamByOrgCodeAndDeptCode(saveDto.getClientOrgCode(), deptCode);
        if (Objects.isNull(sysDepartParam) && StrUtil.isBlank(sysDepartParam.getSignUrl())) {
            throw new BusinessException("无委托机构对应配置参数或签章");
        }
        hashMap.put("signFingerprint", sysDepartParam.getSignUrl());
        // 签章时间
        String signatureTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy年M月d日"));
        hashMap.put("signFingerprintDate", signatureTime);
    }

    /**
     * 填充 案发时间 违法地点  违法行为  违法代码
     * @param saveDto
     * @param hashMap
     */
    private void handleIllegalInformation(SimpleCaseSaveDto saveDto, HashMap hashMap) {
        String formatStr = "yyyy-M-d HH:mm";
        LocalDateTime localDateHappenTime = BaseUtil.stringToLocalDateTime(saveDto.getCaseHappenTime(), formatStr);
        String happenTime = localDateHappenTime.toLocalDate().format(DateTimeFormatter.ofPattern("yyyy年M月d日"));
        happenTime = happenTime + localDateHappenTime.getHour() + "时" + localDateHappenTime.getMinute() + "分";
        hashMap.put("wfrq", happenTime);
        hashMap.put("wfdd", saveDto.getCaseHappenAddressDetail());
        hashMap.put("wfxw", saveDto.getCaseReasonName());
        hashMap.put("wfdm", "(代码" + saveDto.getItemCode() + ")");
    }

    /**
     * 根据当事人类型填充对应的当事人证件信息
     * @param saveDto
     * @param hashMap
     */
    private void handleCertType(SimpleCaseSaveDto saveDto, HashMap hashMap) {
        if (PartyTypeEnum.PERSON.getCode().equals(saveDto.getPartyType())) {
            hashMap.put("sfzmc", CertTypeEnum.getValueByCode(saveDto.getCertType()));
        } else {
            hashMap.put("sfzmc", "社会统一信用代码");
            hashMap.put("certNo", saveDto.getUniscid());
            hashMap.put("mobile", saveDto.getPhone());
        }
    }

    /**
     * 处理扩展信息参数
     *
     * @param saveDto
     * @param hashMap
     */
    private static void dealExtractJsonParams(SimpleCaseSaveDto saveDto, HashMap hashMap) {
        String dataSource;
        String extraJsonInfo = saveDto.getExtraJsonInfo();
        if (!ObjectUtils.isEmpty(extraJsonInfo) && !ApiVisitDataSourceEnum.TASKCENTER.getCode().equals(saveDto.getCaseSourceAppId())) {
            JSONObject jsonObject = JSONObject.parseObject(extraJsonInfo);
            Object dataSourceObj = jsonObject.get("dataSource");
            if (ObjectUtils.isEmpty(dataSourceObj)) {
                throw new BusinessException("未指定数据来源");
            }
            dataSource = (String) dataSourceObj;
            if (ApiVisitDataSourceEnum.isOutSystem(dataSource)) {
                hashMap.put("DATA_SOURCE", dataSource);
            }
        }
    }

    /**
     * 获取案发时间
     */
    private static String getHappenTimeStr(String caseHappenTime, String formatter) {
        //文书日期格式(不要0)
        String formatStr = "yyyy-M-d HH:mm";
        LocalDateTime happenTime = BaseUtil.stringToLocalDateTime(caseHappenTime, formatStr);
        if (ObjectUtils.isEmpty(happenTime)) {
            throw new BusinessException("案件发生日期格式不匹配,应为" + formatStr + ",实际为:" + caseHappenTime);
        }
        return happenTime.toLocalDate().format(DateTimeFormatter.ofPattern(formatter));
    }

    /**
     * 处理当事人信息
     *
     * @param saveDto
     * @param hashMap
     */
    private static void dealDocumentPartInfo(SimpleCaseSaveDto saveDto, HashMap hashMap) {
        if (PartyTypeEnum.PERSON.getCode().equals(saveDto.getPartyType())) {
            hashMap.put("partyName", saveDto.getName());
            hashMap.put("partyCertNo", saveDto.getCertNo());
            hashMap.put("partyAddress", saveDto.getAddress());
            return;
        }
        hashMap.put("partyName", saveDto.getEntName());
        hashMap.put("partyCertNo", saveDto.getUniscid());
        hashMap.put("partyAddress", saveDto.getUnitAddress());
    }

    /**
     * 简易处罚决定书文书参数处理
     *
     * @param saveDto
     * @param hashMap
     * @param userInfo
     */
    private void dealJycxcfjdsDocumentParams(SimpleCaseSaveDto saveDto, HashMap hashMap, UserDTO userInfo) {
        //处理案情描述
        dealCaseDesc(saveDto, hashMap);

        //责令整改描述
        //4.1、立即改正：显示“立即改正”
        //4.2、限期改正：显示“YYYY年MM月DD日前完成改正”
        //4.3、其他：显示具体的内容
        dealCorrectDesc(saveDto, hashMap);

        //处罚描述
        //5.1、仅包含罚款：显示“人民币XX（数额大写）元（ ￥ xx（阿拉伯数字）的处罚”
        //5.2、包含警告和罚款：显示“警告+并+罚款内容”
        dealPunishDesc(saveDto, hashMap);


                /*Example departExample = new Example(SysDepartParam.class);
                departExample.createCriteria().andEqualTo("orgCode", userInfo.getOrgCode());
                List<SysDepartParam> list = sysDepartParamMapper.selectByExample(departExample);*/
        //处理机构信息&机构文书抬头标准名称
        dealJg(saveDto, hashMap, userInfo);
    }

    /**
     * 处理案情描述
     *
     * @param saveDto
     * @param hashMap
     */
    private static void dealCaseDesc(SimpleCaseSaveDto saveDto, HashMap hashMap) {
        //案情描述
        //当事人+于+发现时间（格式：YYYY年MM月DD日）+在+取证地址+因+案由（ 去掉案由头的“对”，尾巴的“的行政处罚）”+违法行为
//                String caseDesc = hashMap.get("partyName") +
//                        "于" +
//                        happenTimeStr +
//                        "在" +
//                        saveDto.getCaseHappenAddressDetail() +
//                        "因" +
//                        BaseUtil.handleCaseReason(saveDto.getCaseReasonName()) + "违法行为";
        //            String illegalFact = saveDto.getIllegalFact();

        String caseDesc = saveDto.getIllegalFact();
        if (caseDesc.endsWith("。") || caseDesc.endsWith(",")) {
            caseDesc = caseDesc.substring(0, caseDesc.length() - 1);
        }
        hashMap.put("caseDesc", caseDesc);
    }

    /**
     * 处理机构信息&文书抬头
     *
     * @param saveDto
     * @param hashMap
     * @param userInfo
     */
    private void dealJg(SimpleCaseSaveDto saveDto, HashMap hashMap, UserDTO userInfo) {
        //定义委托部门code
        String clientDeptCode = null;
        //定义组织名称
        String orgStandardName = null;
        //判断是否是委托事项
        if ("4".equals(saveDto.getSxType())) {
            //去部门参数表中通过orgcode查询deptcode
            Example sysDepartParamExample = new Example(SysDepartParam.class);
            sysDepartParamExample.createCriteria().andEqualTo("orgCode", saveDto.getClientOrgCode());
            List<SysDepartParam> sysDepartParams = sysDepartParamMapper.selectByExample(sysDepartParamExample);
            for (SysDepartParam sysDepartParam : sysDepartParams) {
                if (!ObjectUtils.isEmpty(sysDepartParam.getDeptCode())) {
                    clientDeptCode = sysDepartParam.getDeptCode();
                }
            }
            orgStandardName = documentSendRecordService.getStandOrgNameByCondition(saveDto.getClientOrgCode(), clientDeptCode);
        } else {
            orgStandardName = documentSendRecordService.getStandOrgName();
        }
        SysDepartParam sysDepartParam = null;
        if ("4".equals(saveDto.getSxType())) {
            sysDepartParam = sysDepartParamService.getPublicSecurityEntrustSysDepartParamByOrgCodeAndDeptCode(saveDto.getClientOrgCode(), clientDeptCode);
        } else {
            sysDepartParam = sysDepartParamService.getSysDepartParamByOrgCodeAndDeptCode(userInfo.getOrgCode(), userInfo.getDeptCode());
        }
        //替换：
        if (sysDepartParam != null) {
            //复议机构
            hashMap.put("JYCXCFJDS_FYJG", sysDepartParam.getAdministrativeGovName());
            //起诉法院
            hashMap.put("JYCXCFJDS_QSFY", sysDepartParam.getAdministrativeActionCourtName());
        }
        //文书抬头
        hashMap.put("orgStandardNameSeal", orgStandardName);
    }

    /**
     * 处罚描述
     *
     * @param saveDto
     * @param hashMap
     */
    private static void dealPunishDesc(SimpleCaseSaveDto saveDto, HashMap hashMap) {
        String punishDesc = "人民币" + ConvertUpMoneyUtil.toChinese(saveDto.getDraftPunishMoney()) + "整（￥" + saveDto.getDraftPunishMoney() + "）的处罚";
        if (saveDto.getPunishKinds().contains("警告") && saveDto.getPunishKinds().contains("罚款")) {
            punishDesc = "警告及" + punishDesc;
        } else if ("警告".equals(saveDto.getPunishKinds())) {
            punishDesc = "警告";
        }
        hashMap.put("punishDesc", punishDesc);
    }

    /**
     * 责令整改描述
     * 4.1、立即改正：显示“立即改正”
     * 4.2、限期改正：显示“YYYY年MM月DD日前完成改正”
     * 4.3、其他：显示具体的内容
     *
     * @param saveDto
     * @param hashMap
     */
    private static void dealCorrectDesc(SimpleCaseSaveDto saveDto, HashMap hashMap) {
        String correctDesc = "";
        if (CorrectWayEnum.IMMEDIATELY_CORRECT.getCode().equals(saveDto.getCorrectWay())) {
            correctDesc = CorrectWayEnum.IMMEDIATELY_CORRECT.getDes();
        } else if (CorrectWayEnum.TIME_CORRECT.getCode().equals(saveDto.getCorrectWay())) {
            String correctEndDate = "";
            if (ObjectUtil.isNotEmpty(saveDto.getCorrectEndDate())) {
                correctEndDate = saveDto.getCorrectEndDate().replaceAll(" ", "");
            }
            correctDesc = correctEndDate + "前完成改正";
        } else {
            correctDesc = saveDto.getCorrectOtherContent();
        }
        hashMap.put("correctDesc", correctDesc);
    }

    /**
     * 现场照片及说明参数处理
     *
     * @param saveDto
     * @param hashMap
     * @param userInfo
     * @param happenTimeStr
     */
    private void dealXczpjsmDocumentParams(SimpleCaseSaveDto saveDto, HashMap hashMap, UserDTO userInfo, String happenTimeStr) {
        //取证单图片处理
        List<Map> evidencePhotoList = new ArrayList<>();
        Example appendixRecord = new Example(CaseAppendixRecord.class);
        appendixRecord.createCriteria().andEqualTo("caseId", saveDto.getCaseId()).andEqualTo("appendixTypeId", AttachmentTypeEnum.EVIDENCE_PHOTO.getCode());
        List<CaseAppendixRecord> caseAppendixRecords = caseAppendixRecordMapper.selectByExample(appendixRecord);
        caseAppendixRecords.forEach(caseAppendixRecord -> {
            evidencePhotoList.add(Collections.singletonMap("evidencePhoto", caseAppendixRecord.getAppendixUrl()));
        });
        hashMap.put("evidencePhotoList", evidencePhotoList);
        //设置拍摄人,制作人
        hashMap.put("userName", userInfo.getRealName());
        hashMap.put("producer", userInfo.getRealName());

        //拍摄时间处理 格式为xxxx年xx月xx日
        hashMap.put("caseHappenTime", happenTimeStr);

        //设置执法证号
        Example queryExample = new Example(CaseHandlePersonRecord.class);
        queryExample.createCriteria().andEqualTo("caseId", saveDto.getCaseId());
        List<CaseHandlePersonRecord> caseHandlePersonRecordList = caseHandlePersonRecordMapper.selectByExample(queryExample);
        caseHandlePersonRecordList.forEach(e -> {
            if (HandlePersonTypeEnum.MAIN.getCode().equals(e.getHandlePersonType())) {
                hashMap.put("mainLawEnforcementCert", e.getLawEnforcementCert());
            } else if (HandlePersonTypeEnum.ASSIST.getCode().equals(e.getHandlePersonType())) {
                hashMap.put("assistLawEnforcementCert", e.getLawEnforcementCert());
            }
        });
    }


    /**
     * 校验案件数据
     *
     * @param saveDto
     * @return
     */
    private String checkSimpleCase(SimpleCaseSaveDto saveDto) {
        String errorMessage = "";
        UserDTO userInfo = UserUtil.getUserInfo();
        //校验当事人信息
        String returnMsg = checkParty(saveDto);
        if (!Constant.STRING_SUCCESS_EN.equals(returnMsg)) {
            return returnMsg;
        }

        //校验立案是否重复
        //案件修改
        if (!ObjectUtils.isEmpty(saveDto.getCaseId())) {
            CaseMainInfo caseMainInfo1 = caseMainInfoMapper.selectByPrimaryKey(saveDto.getCaseId());
            if (ObjectUtils.isEmpty(caseMainInfo1)) {
                throw new BusinessException("案件信息不存在");
            }
            //判断当事人是否修改
            Example example = new Example(CasePartiesRecord.class);
            example.createCriteria().andEqualTo("caseId", saveDto.getCaseId()).andEqualTo("status", "1");
            List<CasePartiesRecord> casePartiesRecords = casePartiesRecordMapper.selectByExample(example);
            if (!casePartiesRecords.isEmpty()) {
                CasePartiesRecord partiesRecord = casePartiesRecords.get(0);
                if ((PartyTypeEnum.PERSON.getCode().equals(partiesRecord.getPartyType()) && partiesRecord.getPartyIdentityCode().equals(saveDto.getCertNo()))
                        || (PartyTypeEnum.LEGAL.getCode().equals(partiesRecord.getPartyType()) && partiesRecord.getPartyIdentityCode().equals(saveDto.getUniscid()))) {
                    return "";
                }
            } else {
                return "";
            }

        }
        //文书日期格式(不要0)
        String formatStr = "yyyy-M-d HH:mm";
        LocalDateTime happenTime = BaseUtil.stringToLocalDateTime(saveDto.getCaseHappenTime(), formatStr);
        if (ObjectUtils.isEmpty(happenTime)) {
            throw new BusinessException("案件发生日期格式不匹配,应为" + formatStr + ",实际为:" + saveDto.getCaseHappenTime());
        }
        String happenTimeStr = happenTime.toLocalDate().format(DateTimeFormatter.ofPattern("yyyy-M-d"));

        String caseReasonCode = saveDto.getCaseReasonCode();
        Map<String, Object> map = new HashMap<>(4);
        map.put("caseReasonCode", caseReasonCode);
        //案件重复改为按每天的小时来判断
        map.put("happenTime", happenTimeStr);
        map.put("caseId", saveDto.getCaseId());

        //个人
        if (PartyTypeEnum.PERSON.getCode().equals(saveDto.getPartyType())) {
            map.put("certNo", saveDto.getCertNo());
            List<String> caseIdList = caseMainDetailSimpleInfoMapper.selectCaseIdByReasonsAndHappenTime(map);
            if (ObjectUtil.isNotEmpty(caseIdList) && caseIdList.size() > 0) {
                throw new BusinessException("当事人(个人)" + saveDto.getName() + saveDto.getCertNo() + "案件信息已存在，请勿重复录入");
            }
        } else {//单位
            //校验统一社会信用代码
            if (!SocialCreditCodeUtil.isValidEntCode(saveDto.getUniscid(), saveDto.getEntType())) {
                throw new BusinessException("统一社会信用代码：" + saveDto.getUniscid() + "不符合规范");
            }
            map.put("uniscid", saveDto.getUniscid());
            List<String> caseIdList = caseMainDetailSimpleInfoMapper.selectCaseIdByReasonsAndHappenTime(map);
            if (ObjectUtil.isNotEmpty(caseIdList) && caseIdList.size() > 0) {
                throw new BusinessException("当事人(单位)" + saveDto.getLegal() + saveDto.getLegalCertNo() + "案件信息已存在，请勿重复录入");
            }
        }

        //是否予以处罚相关信息校验
        if (Constant.STRING_1.equals(saveDto.getIsSlightIllegal())
                && Constant.STRING_2.equals(saveDto.getInvestConclusion())) {
            if (ObjectUtils.isEmpty(saveDto.getNotGivePunishReason())) {
                throw new BusinessException("案件不予处罚时,不予处罚原因不能为空");
            }
        } else {
            if (ObjectUtils.isEmpty(saveDto.getPunishKinds())) {
                throw new BusinessException("案件予以处罚时,拟处罚内容不能为空");
            }
            if (saveDto.getPunishKinds().contains("罚款")) {
                if (ObjectUtils.isEmpty(saveDto.getDraftPunishMoney())) {
                    throw new BusinessException("案件予以处罚且罚款时,拟处罚金额不能为空");
                }
                if (ObjectUtils.isEmpty(saveDto.getPayWay())) {
                    throw new BusinessException("案件予以处罚且罚款时,缴款方式不能为空");
                }
            }

        }
        // 校验办案人员信息
        List<CaseHandlePersonInfoDto> caseHandlePersonInfoDtoList = saveDto.getHandlePersonInfoList();
        List<CaseHandlePersonInfoDto> mainHandlePersonList = caseHandlePersonInfoDtoList.stream().filter(e -> Constant.STRING_1.equals(e.getHandlePersonType())).collect(Collectors.toList());
        if (ObjectUtil.isEmpty(mainHandlePersonList) || mainHandlePersonList.size() < 1) {
            throw new BusinessException("主办人员不能为空");
        }
        List<CaseHandlePersonInfoDto> assistHandlePersonList = caseHandlePersonInfoDtoList.stream().filter(e -> Constant.STRING_2.equals(e.getHandlePersonType())).collect(Collectors.toList());
        if (ObjectUtil.isEmpty(assistHandlePersonList) || assistHandlePersonList.size() < 1) {
            throw new BusinessException("协办人员不能为空");
        }
        List<String> repeatHandlePersonList = caseHandlePersonInfoDtoList.stream().map(CaseHandlePersonInfoDto::getHandlePersonId).distinct().collect(Collectors.toList());
        if (ObjectUtil.isEmpty(repeatHandlePersonList) || caseHandlePersonInfoDtoList.size() != repeatHandlePersonList.size()) {
            throw new BusinessException("主办人员、协办人员不能重复");
        }
        return errorMessage;
    }

    /*
     * 校验当事人信息
     */
    private String checkParty(SimpleCaseSaveDto saveDto) {
        //个人
        if (PartyTypeEnum.PERSON.getCode().equals(saveDto.getPartyType())) {
            if (StringUtils.isEmpty(saveDto.getCertNo())) {
                return "请输入个人-当事人证件号";
            } else if (StringUtils.isEmpty(saveDto.getName())) {
                return "请输入个人-当事人姓名";
            } else if (StringUtils.isEmpty(saveDto.getCertType())) {
                return "请输入个人-证件类型";
            } else if (StringUtils.isEmpty(saveDto.getAddress())) {
                return "请输入个人-住址";
            }

            if ("SFZ".equals(saveDto.getCertType())) {
                //校验身份证与姓名是否匹配
                boolean checkCert = checkRealName(saveDto.getName(), saveDto.getCertNo());
                if (!checkCert) {
                    return "个人-姓名身份证不匹配！";
                }
            }

            //单位
        } else if (PartyTypeEnum.LEGAL.getCode().equals(saveDto.getPartyType())) {
            if (StringUtils.isEmpty(saveDto.getUniscid())) {
                return "请输入单位-统一社会信用代码";
            } else if (StringUtils.isEmpty(saveDto.getLegal())) {
                return "请输入单位-法定代表人或负责人姓名";
            } else if (StringUtils.isEmpty(saveDto.getEntName())) {
                return "请输入单位-名称";
            } else if (StringUtils.isEmpty(saveDto.getUnitAddress())) {
                return "请输入单位-住所";
            }

            if ("SFZ".equals(saveDto.getLegalCertType())) {
                //校验身份证与姓名是否匹配
                boolean checkCert = checkRealName(saveDto.getLegal(), saveDto.getLegalCertNo());
                if (!checkCert) {
                    return "法定代表人/负责人-姓名身份证不匹配！";
                }
            }

        } else {
            return "当事人类型有误";
        }
        return Constant.STRING_SUCCESS_EN;
    }

    /**
     * 1、处理案件主表及详情表数据
     *
     * @param saveDto
     * @param userInfo
     */
    public void dealCaseMainInfo(SimpleCaseSaveDto saveDto, UserDTO userInfo) {
        LocalDateTime nowDate = LocalDateTime.now();
        //1、 组装主表数据
        CaseMainInfo caseMainInfo = new CaseMainInfo();
        BeanUtils.copyProperties(saveDto, caseMainInfo);
//        List<Territory> permissionTerritoryList = userInfo.getPermissionTerritoryList();
//        if (ObjectUtil.isNotEmpty(permissionTerritoryList)){
//            Territory territory = permissionTerritoryList.get(0);
//            caseMainInfo.setCaseTerritoryCode(territory.getCode());
//            caseMainInfo.setCaseTerritoryName(territory.getName());
//        }
        String orgCode = userInfo.getOrgCode();
        //条线编码
        String lineCode = saveDto.getLineCode();
        String lineName = saveDto.getLineName();
        if (ObjectUtils.isEmpty(lineCode)) {
            List<LineTerritoryInfoVo> lineTerritoryInfoVos = sysDepartParamService.getLineInfoListByOrgCode(orgCode);
            // todo 目前只维护一个条线，暂时取第一个条线
            lineTerritoryInfoVos = lineTerritoryInfoVos.stream().filter(e -> Constant.STRING_1.equals(e.getLineCaseHandleStatusCode())).collect(Collectors.toList());
            LineTerritoryInfoVo lineTerritoryInfoVo = new LineTerritoryInfoVo();
            if (lineTerritoryInfoVos.size() == 1) {
                lineTerritoryInfoVo = lineTerritoryInfoVos.get(0);
            } else {
                List<LineTerritoryInfoVo> reasonTerritory = lineTerritoryInfoVos.stream().filter(e -> e.getLineCode().contains(saveDto.getTerritoryCode())).collect(Collectors.toList());
                if (ObjectUtil.isNotEmpty(reasonTerritory) && reasonTerritory.size() > 0) {
                    lineTerritoryInfoVo = reasonTerritory.get(0);
                } else {
                    lineTerritoryInfoVo = lineTerritoryInfoVos.get(0);
                }

            }
            lineCode = lineTerritoryInfoVo.getLineCode();
            lineName = lineTerritoryInfoVo.getLineName();
        }

        LineTerritoryInfoVo lineInfoByOrgCodeAndLineCode = sysDepartParamService.getLineInfoByOrgCodeAndLineCode(userInfo.getOrgCode(), lineCode);

        caseMainInfo.setLineCode(lineCode);
        caseMainInfo.setLineName(lineName);
        caseMainInfo.setCaseTerritoryCode(lineInfoByOrgCodeAndLineCode.getTerritoryCode());
        caseMainInfo.setCaseTerritoryName(lineInfoByOrgCodeAndLineCode.getTerritoryName());
        caseMainInfo.setCaseStatus(CaseStatusEnum.TEMP.getCode());
        caseMainInfo.setCaseAreaCode(userInfo.getAreaCode());
        //案件名称处理
        String partyName = "";
        if (PartyTypeEnum.PERSON.getCode().equals(saveDto.getPartyType())) {
            partyName = saveDto.getName();
        } else {
            partyName = saveDto.getEntName();
        }
        String caseReasonName = BaseUtil.handleCaseReason(saveDto.getCaseReasonName() + "案");
        String caseName = partyName + "涉嫌" + caseReasonName;
        if (StringUtils.isNotBlank(saveDto.getCaseName())) {
            caseName = saveDto.getCaseName();
        }

        caseMainInfo.setCaseName(caseName);
        caseMainInfo.setCaseOrgCode(userInfo.getOrgCode());
        caseMainInfo.setCaseOrgName(userInfo.getOrgName());
        caseMainInfo.setCaseDeptCode(userInfo.getDeptCode());
        caseMainInfo.setCaseDeptName(userInfo.getDeptName());
        //设置案件类型--简易处罚
        caseMainInfo.setCaseType(CaseTypeEnum.SIMPLE_PROCEDURE.getCode());
        //案件来源定死--巡查中发现
        caseMainInfo.setCaseSource("巡查中发现");

        caseMainInfo.setCaseCurrentStageCode("CASE_REGISTER");
        caseMainInfo.setCaseCurrentStageName("立案");
        caseMainInfo.setCaseCurrentLinkCode("LINK-202203020938");
        caseMainInfo.setCaseCurrentLinkName("立案登记");

        //获取领域下业务参数Id
        RelationWorkflowInfoRequest request = new RelationWorkflowInfoRequest();
        request.setApplyAreaCode(userInfo.getAreaCode());
        String applyFieldCode = lineInfoByOrgCodeAndLineCode.getTerritoryCode();
        request.setApplyFieldCode(applyFieldCode);
        if ("A037".equals(applyFieldCode)) {
            request.setApplyAreaCode(null);
        }
        List<ConfigBusiParamMain> configBusiParamMainList = configBusiParamMainService.getConfigBusiParamMainList(request);
        String busiParamId = configBusiParamMainList.get(0).getId();
        caseMainInfo.setBusiParamId(busiParamId);

        //2、组装宽表数据
        CaseMainDetailSimpleInfo caseMainDetailSimpleInfo = new CaseMainDetailSimpleInfo();
        CaseMainDetailAuxiliaryInfo caseMainDetailAuxiliaryInfo = new CaseMainDetailAuxiliaryInfo();
        BeanUtils.copyProperties(saveDto, caseMainDetailSimpleInfo);
        BeanUtils.copyProperties(saveDto, caseMainDetailAuxiliaryInfo);
        //校验处罚金额
        try {
            if (!ObjectUtils.isEmpty(caseMainDetailSimpleInfo.getDraftPunishMoney())) {
                Double.valueOf(caseMainDetailSimpleInfo.getDraftPunishMoney());
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("处罚金额格式错误,金额为" + caseMainDetailSimpleInfo.getDraftPunishMoney());
        }
        //文书日期格式(不要0)
        String formatStr = "yyyy-M-d HH:mm";
        LocalDateTime happenTime = BaseUtil.stringToLocalDateTime(saveDto.getCaseHappenTime(), formatStr);
        if (ObjectUtils.isEmpty(happenTime)) {
            throw new BusinessException("案件发生日期格式不匹配,应为" + formatStr + ",实际为:" + saveDto.getCaseHappenTime());
        }
        caseMainDetailSimpleInfo.setCaseHappenTime(happenTime);
        caseMainDetailSimpleInfo.setCaseReason(saveDto.getCaseReasonName());
        caseMainDetailSimpleInfo.setCaseContent(JSONObject.toJSONString(saveDto));
        caseMainDetailSimpleInfo.setUpdateTime(nowDate);


        if (StringUtils.isNotBlank(saveDto.getCorrectEndDate())) {
            //文书日期格式(不要0)
            String formatStrCn = "yyyy年M月d日 HH时";
            try {
                LocalDateTime correctEndDate = BaseUtil.stringToLocalDateTime(saveDto.getCorrectEndDate(), formatStrCn);
                caseMainDetailSimpleInfo.setCorrectEndDate(correctEndDate);
            } catch (Exception e) {
                throw new BusinessException("整改截止日期格式不匹配,应为" + formatStrCn + ",实际为:" + saveDto.getCorrectEndDate());
            }
        }
        if (!ObjectUtils.isEmpty(saveDto.getCaseSourceAppId())) {
            caseMainInfo.setDataSource(saveDto.getCaseSourceAppId());
        }
        if (!ObjectUtils.isEmpty(saveDto.getDataSourceServiceId())) {
            caseMainInfo.setDataSourceServiceId(saveDto.getDataSourceServiceId());
        }

        String dataSource;
        String extraJsonInfo = saveDto.getExtraJsonInfo();
        if (!ObjectUtils.isEmpty(extraJsonInfo) && !ApiVisitDataSourceEnum.TASKCENTER.getCode().equals(saveDto.getCaseSourceAppId())) {
            JSONObject jsonObject = JSONObject.parseObject(extraJsonInfo);
            Object dataSourceObj = jsonObject.get("dataSource");
            if (ObjectUtils.isEmpty(dataSourceObj)) {
                throw new BusinessException("未指定数据来源");
            }
            dataSource = (String) dataSourceObj;
            if (ApiVisitDataSourceEnum.isOutSystem(dataSource)) {
                String dataSourceServiceId = saveDto.getDataSourceServiceId();
                caseMainInfo.setDataSource(dataSource);
                if (ObjectUtils.isEmpty(dataSourceServiceId)) {
                    //获取缓存中的dataSourceServiceId
                    SimpleCaseQueryDto queryDto = new SimpleCaseQueryDto();
                    SimpleCaseInfoVo vo = getCaseRegisterDetailSimpleInfo(queryDto);
                    caseMainInfo.setDataSourceServiceId(vo.getDataSourceServiceId());
                }
            }
        }

        //执行方式--定死自觉履行 （提交时再更新执行方式）
        //   caseMainDetailSimpleInfo.setExecuteWay("自觉履行");
        if (ObjectUtil.isEmpty(saveDto.getCaseId())) {
            caseMainInfo.setId(BaseUtil.createUid());
            caseMainInfo.setCaseCreateTime(nowDate);

            caseMainInfoMapper.insertSelective(caseMainInfo);
            //新增宽表
            caseMainDetailSimpleInfo.setCreateTime(nowDate);
            caseMainDetailSimpleInfo.setId(BaseUtil.createUid());
            caseMainDetailSimpleInfo.setCaseId(caseMainInfo.getId());
            caseMainDetailSimpleInfoMapper.insertSelective(caseMainDetailSimpleInfo);
            try {
                caseMainDetailAuxiliaryInfo.setId(BaseUtil.createUid());
                caseMainDetailAuxiliaryInfo.setCaseId(caseMainInfo.getId());
                caseMainDetailAuxiliaryInfo.setCaseReasonId(BaseUtil.createUid());
                caseMainDetailAuxiliaryInfo.setInvestConclusion(Constant.STRING_1);
                caseMainDetailAuxiliaryInfoMapper.insertSelective(caseMainDetailAuxiliaryInfo);
            } catch (Exception e) {
                e.printStackTrace();
            }
            //将caseId放入saveDto
            saveDto.setCaseId(caseMainInfo.getId());
        } else {
            //检查条线是否切换,条线变化删除之前的文书记录
            CaseMainInfo oldCaseMainInfo = caseMainInfoMapper.selectByPrimaryKey(saveDto.getCaseId());
            if (!lineCode.equals(oldCaseMainInfo.getLineCode())) {
                Example docExample = new Example(CaseDocumentRecord.class);
                docExample.createCriteria().andEqualTo("caseId", saveDto.getCaseId());
                caseDocumentRecordMapper.deleteByExample(docExample);
            }

            //更新主表数据
            caseMainInfo.setId(saveDto.getCaseId());
            caseMainInfoMapper.updateByPrimaryKeySelective(caseMainInfo);
            //更新宽表数据
            CaseMainDetailSimpleInfo oldDetailSimpleInfo = caseMainDetailSimpleInfoService.getCaseMainDetailSimpleInfo(saveDto.getCaseId());
            /*CaseMainDetailAuxiliaryInfo oldcaseMainDetailAuxiliaryInfo=caseMainDetailAuxiliaryInfoMapper.selectCaseMainDetailAuxiliaryInfoByCaseId(saveDto.getCaseId());*/
            Example example = new Example(CaseMainDetailAuxiliaryInfo.class);
            example.createCriteria().andEqualTo("caseId", saveDto.getCaseId());
            List<CaseMainDetailAuxiliaryInfo> caseMainDetailAuxiliaryInfos = caseMainDetailAuxiliaryInfoMapper.selectByExample(example);
            if (!ObjectUtils.isEmpty(oldDetailSimpleInfo)) {
                caseMainDetailSimpleInfo.setCaseId(caseMainInfo.getId());
                caseMainDetailSimpleInfo.setId(oldDetailSimpleInfo.getId());
                caseMainDetailSimpleInfoMapper.updateByPrimaryKeySelective(caseMainDetailSimpleInfo);
            }
            if (!ObjectUtils.isEmpty(caseMainDetailAuxiliaryInfos)) {
                CaseMainDetailAuxiliaryInfo oldCaseMainDetailAuxiliaryInfo = caseMainDetailAuxiliaryInfos.get(0);
                caseMainDetailAuxiliaryInfo.setId(oldCaseMainDetailAuxiliaryInfo.getId());
                caseMainDetailAuxiliaryInfoMapper.updateByPrimaryKeySelective(caseMainDetailAuxiliaryInfo);
            }


        }
        //3、保存取证照片信息
        //删除之前的取证照片
        Example example = new Example(CaseAppendixRecord.class);
        example.createCriteria().andEqualTo("caseId", saveDto.getCaseId()).andEqualTo("appendixTypeId", AttachmentTypeEnum.EVIDENCE_PHOTO.getCode());
        caseAppendixRecordMapper.deleteByExample(example);
        List<CaseEvidencePhotoDto> caseEvidencePhotoList = saveDto.getCaseEvidencePhotoList();
        if (!ObjectUtils.isEmpty(caseEvidencePhotoList)) {
            for (CaseEvidencePhotoDto photoDto : caseEvidencePhotoList) {
                CaseAppendixRecord record = new CaseAppendixRecord();
                record.setCaseId(saveDto.getCaseId());
                record.setAppendixUrl(photoDto.getFileUrl());
                record.setAppendixTypeId(AttachmentTypeEnum.EVIDENCE_PHOTO.getCode());
                record.setAppendixName(photoDto.getFileName());
                record.setId(BaseUtil.createUid());
                record.setUploadTime(LocalDateTime.now());
                record.setUploadUserId(userInfo.getUserId().toString());
                record.setUploadUserName(userInfo.getRealName());
                record.setIsDelete(Constant.STRING_0);
                record.setAppendixStatus(Constant.STRING_1);
                caseAppendixRecordMapper.insertSelective(record);
            }
        }

    }

    /**
     * 描述：2、处理案件登记，保存案由信息
     */
    private void dealCaseReasonInfo(SimpleCaseSaveDto saveDto) {

        //之前老数据更新为失效
        Example example = new Example(CaseReasonMainRecord.class);
        example.createCriteria().andEqualTo("caseId", saveDto.getCaseId());
        List<CaseReasonMainRecord> recordList = caseReasonMainRecordMapper.selectByExample(example);
        if (recordList != null && recordList.size() > 0) {
            for (CaseReasonMainRecord record : recordList) {
                record.setStatus(Constant.STRING_0);
                caseReasonMainRecordMapper.updateByPrimaryKey(record);
            }
        }

        CaseReasonMainRecord caseReasonMainRecord = new CaseReasonMainRecord();
        BeanUtils.copyProperties(saveDto, caseReasonMainRecord);
        caseReasonMainRecord.setCreateTime(LocalDateTime.now());
        caseReasonMainRecord.setId(BaseUtil.createUid());
        caseReasonMainRecord.setCaseReasonNameSimple(BaseUtil.handleCaseReason(saveDto.getCaseReasonName()));
        caseReasonMainRecord.setIllegalBasisFormat(BaseUtil.removeHtml(saveDto.getIllegalBasis()));
        caseReasonMainRecord.setIllegalDetailFormat(BaseUtil.removeHtml(saveDto.getIllegalDetail()));
        caseReasonMainRecord.setPunishBasisFormat(BaseUtil.removeHtml(saveDto.getPunishBasis()));
        caseReasonMainRecord.setPunishDetailFormat(BaseUtil.removeHtml(saveDto.getPunishDetail()));
        caseReasonMainRecord.setStatus(Constant.STRING_1);
        if (ObjectUtil.isNotEmpty(saveDto.getSxType())) {
            caseReasonMainRecord.setSxType(saveDto.getSxType());
        }
        if (ObjectUtil.isNotEmpty(saveDto.getClientOrgCode())) {
            caseReasonMainRecord.setClientOrgCode(saveDto.getClientOrgCode());
        }
        if (ObjectUtil.isNotEmpty(saveDto.getClientOrgName())) {
            caseReasonMainRecord.setClientOrgName(saveDto.getClientOrgName());
        }
        if (ObjectUtil.isNotEmpty(saveDto.getAreaCode())) {
            caseReasonMainRecord.setAreaCode(saveDto.getAreaCode());
        }
        if (ObjectUtil.isNotEmpty(saveDto.getClientLineCode())) {
            caseReasonMainRecord.setClientLineCode(saveDto.getClientLineCode());
        }
        if (ObjectUtil.isNotEmpty(saveDto.getItemCode())) {
            caseReasonMainRecord.setPublicSecurityItemCode(saveDto.getItemCode());
        }
        if (ObjectUtil.isNotEmpty(saveDto.getCatalogId())) {
            caseReasonMainRecord.setItemRelationCode(saveDto.getCatalogId());
        }
        caseReasonMainRecordMapper.insertSelective(caseReasonMainRecord);
    }

    /**
     * 描述：3、处理案件登记，办案人员信息
     */
    private void dealCaseHandlePersonInfo(SimpleCaseSaveDto saveDto, UserDTO userInfo) {
        List<CaseHandlePersonInfoDto> caseHandlePersonInfoDtoList = saveDto.getHandlePersonInfoList();
        String caseId = saveDto.getCaseId();
        //删除之前的办案人员
        Example example = new Example(CaseHandlePersonRecord.class);
        example.createCriteria().andEqualTo("caseId", caseId);
        caseHandlePersonRecordMapper.deleteByExample(example);
        for (CaseHandlePersonInfoDto handlePersonInfoDto : caseHandlePersonInfoDtoList) {
            CaseHandlePersonRecord caseHandlePersonRecord = new CaseHandlePersonRecord();
            BeanUtils.copyProperties(handlePersonInfoDto, caseHandlePersonRecord);
            caseHandlePersonRecord.setHandlePersonType(handlePersonInfoDto.getHandlePersonType());
            caseHandlePersonRecord.setDingId(handlePersonInfoDto.getDingId());
            if (ObjectUtil.isNotEmpty(handlePersonInfoDto.getHandlePersonId())) {
                caseHandlePersonRecord.setLawEnforcementCert(xzzfInterfaceService.getLawEnforcementCertWithUserId(handlePersonInfoDto.getHandlePersonId()));
            }
            //  签名校验
            String handlePersonSignPic = appCaseBeforeDocumentRecordService.getHandleSignData(handlePersonInfoDto.getHandlePersonId());
            if ("true".equals(isCheckHandleSign)) {
                if (ObjectUtil.isEmpty(handlePersonSignPic)) {
                    throw new BusinessException("办案人员" + handlePersonInfoDto.getHandlePersonName() + "的签名为空!");
                }
            }
            caseHandlePersonRecord.setHandleSignPic(handlePersonSignPic);
            caseHandlePersonRecord.setId(BaseUtil.createUid());
            caseHandlePersonRecord.setCaseId(caseId);
            caseHandlePersonRecord.setHandleOrgCode(userInfo.getOrgCode());
            caseHandlePersonRecord.setHandleOrgName(userInfo.getOrgName());

            String telPhone = userInfo.getTelPhone();
            caseHandlePersonRecord.setHandleOrgTel(telPhone);
            caseHandlePersonRecord.setHandleDeptCode(userInfo.getDeptCode());
            caseHandlePersonRecord.setHandleDeptName(userInfo.getDeptName());
            caseHandlePersonRecord.setHandleDeptTel(userInfo.getTelPhone());
            caseHandlePersonRecordMapper.insertSelective(caseHandlePersonRecord);
        }

    }

    /**
     * 描述：4、处理案件登记，保存当事人信息
     */
    public void dealCasePartiesInfo(SimpleCaseSaveDto saveDto) {
        String id = "";
        String partyId = "";
        boolean isLegal = false;
        //判断当事人信息是否存在
        Example example = new Example(CasePartiesRecord.class);
        example.createCriteria().andEqualTo("caseId", saveDto.getCaseId()).andEqualTo("status", "1");
        List<CasePartiesRecord> casePartiesRecords = casePartiesRecordMapper.selectByExample(example);
        if (!ObjectUtils.isEmpty(casePartiesRecords)) {
            CasePartiesRecord partiesRecord = casePartiesRecords.get(0);
            id = partiesRecord.getId();
            partyId = partiesRecord.getPartyId();

            //删除历史当事人信息
            casePartiesPersonInfoMapper.deleteByPrimaryKey(partyId);
            casePartiesLegalInfoMapper.deleteByPrimaryKey(partyId);

        }

        //新增或修改当事人信息
        if (PartyTypeEnum.PERSON.getCode().equals(saveDto.getPartyType())) {
            CasePartiesPersonInfo personInfo = new CasePartiesPersonInfo();

            personInfo.setAddress(saveDto.getAddress());
            personInfo.setAge(saveDto.getAge());
            personInfo.setCertNo(saveDto.getCertNo());
            personInfo.setCertType(saveDto.getCertType());
            personInfo.setMobile(saveDto.getMobile());
            personInfo.setJob(saveDto.getJob());
            personInfo.setName(saveDto.getName());
            personInfo.setSex(saveDto.getSex());
            personInfo.setUnitName(saveDto.getUnitName());
            personInfo.setNationality(saveDto.getNationality());

            if (ObjectUtils.isEmpty(partyId)) {
                personInfo.setId(BaseUtil.createUid());
                partyId = personInfo.getId();
            } else {
                personInfo.setId(partyId);
            }
            casePartiesPersonInfoMapper.insertSelective(personInfo);

        } else {
            //3.添加当事人(公司)法人表
            isLegal = true;
            CasePartiesLegalInfo legalInfo = new CasePartiesLegalInfo();

            legalInfo.setAddress(saveDto.getUnitAddress());
            legalInfo.setLegalName(saveDto.getLegal());
            legalInfo.setPhone(saveDto.getPhone());
            legalInfo.setUniscid(saveDto.getUniscid());
            legalInfo.setEntName(saveDto.getEntName());
            legalInfo.setJob(saveDto.getJob());
            legalInfo.setEntType(saveDto.getEntType());
            legalInfo.setLegalCertType(saveDto.getLegalCertType());
            legalInfo.setLegalCertNo(saveDto.getLegalCertNo());
            if (StringUtils.isEmpty(saveDto.getLegalCertNo())) {
                legalInfo.setLegalCertNo(getFrCertNo(saveDto.getUniscid(), saveDto.getEntName()));
            }
            legalInfo.setBusinessAddress(saveDto.getBusinessAddress());

            if (ObjectUtils.isEmpty(partyId)) {
                legalInfo.setId(BaseUtil.createUid());
                partyId = legalInfo.getId();
            } else {
                legalInfo.setId(partyId);
            }
            casePartiesLegalInfoMapper.insertSelective(legalInfo);

        }
        //4 更新当事人记录表
        CasePartiesRecord partiesRecord = new CasePartiesRecord();
        partiesRecord.setCreateTime(LocalDateTime.now());
        partiesRecord.setCaseId(saveDto.getCaseId());
        partiesRecord.setPartyId(partyId);
        partiesRecord.setPartyIdentityCode(saveDto.getCertNo());
        partiesRecord.setPartyIdentityType(saveDto.getCertType());
        partiesRecord.setPartyName(saveDto.getName());
        partiesRecord.setPartyType(PartyTypeEnum.PERSON.getCode());
        if (isLegal) {
            partiesRecord.setPartyType(PartyTypeEnum.LEGAL.getCode());
            partiesRecord.setPartyIdentityCode(saveDto.getUniscid());
            partiesRecord.setPartyIdentityType(null);
            partiesRecord.setPartyName(saveDto.getEntName());
        }
        if (ObjectUtils.isEmpty(id)) {
            partiesRecord.setId(BaseUtil.createUid());
            casePartiesRecordMapper.insertSelective(partiesRecord);
        } else {
            partiesRecord.setId(id);
            casePartiesRecordMapper.updateByPrimaryKeySelective(partiesRecord);
        }

        saveDto.setPartyId(partyId);

    }

    /**
     * 手动或者未传企业当事人法人身份证时，在调用一次法人库获取信息；
     *
     * @param uniscid 统一代码
     * @param company 公司名称
     * @return String
     */
    private String getFrCertNo(String uniscid, String company) {
        if (StringUtils.isEmpty(uniscid) && StringUtils.isEmpty(company)) {
            return "";
        }
        EntQueryDto entQueryDto = new EntQueryDto();
        entQueryDto.setTyxydm(uniscid);
        entQueryDto.setFrmc(company);
        JSONArray array = appCaseBeforeDocumentRecordService.getEntList(entQueryDto);
        if (array == null || array.size() == 0) {
            return "";
        } else if (array.size() == 1) {
            JSONObject obj = (JSONObject) array.get(0);
            return obj.getString("fr_zjhm");
        } else {
            return "";
        }

    }


    /**
     * 描述： 查询简易案件录入数据
     *
     * @return {@link JSONObject}
     * @author: zhengqiang
     * @date: 2022/6/20
     * @param: queryDto
     **/
    @Override
    public SimpleCaseInfoVo getCaseRegisterDetailSimpleInfo(SimpleCaseQueryDto queryDto) {
        UserDTO userInfo = UserUtil.getUserInfo();

        SimpleCaseInfoVo vo = new SimpleCaseInfoVo();

        String caseId = queryDto.getCaseId();
        CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(caseId);
        if (ObjectUtil.isNotEmpty(caseId)
                && CaseStatusEnum.SIMPLE_CASE_REVOKE.getCode().equals(caseMainInfo.getCaseStatus())) {
            vo.setCaseStatus(caseMainInfo.getCaseStatus());
            Example example = new Example(CaseDocumentRecord.class);
            example.createCriteria().andEqualTo("caseId", caseId);
            example.orderBy("document_create_time desc");
            List<CaseDocumentRecord> caseDocumentRecordList = caseDocumentRecordMapper.selectByExample(example);
            CaseDocumentRecord record = caseDocumentRecordList.get(0);
            String caseContent = record.getDocumentContent();
            vo = JSONObject.parseObject(caseContent, SimpleCaseInfoVo.class);
            vo.setIsAutoSave(Constant.STRING_0);
            vo.setDataSource(caseMainInfo.getDataSource());
            vo.setDataSourceServiceId(caseMainInfo.getDataSourceServiceId());
        } else {
            //查询当前用户的暂存记录
            Example queryExample = new Example(CaseTemporaryRecord.class);
            queryExample.createCriteria().andEqualTo("addUser", userInfo.getLoginName())
                    .andEqualTo("caseId", "EMPTY").andEqualTo("orgCode", userInfo.getOrgCode());
            List<CaseTemporaryRecord> caseTemporaryRecords = caseTemporaryRecordMapper.selectByExample(queryExample);
            if (!ObjectUtils.isEmpty(caseTemporaryRecords)) {
                CaseTemporaryRecord record = caseTemporaryRecords.get(0);
                String dataSource = record.getDataSource();
                String caseContent = record.getContent();
                vo = JSONObject.parseObject(caseContent, SimpleCaseInfoVo.class);
                List<CaseEvidencePhotoDto> caseEvidencePhotoList = vo.getCaseEvidencePhotoList();
                if (!ObjectUtils.isEmpty(caseEvidencePhotoList)) {
                    caseEvidencePhotoList.forEach(e -> {
                        e.setFileBase64Info(null);
                        if (ApiVisitDataSourceEnum.TASKCENTER.getCode().equals(dataSource)) {
                            e.setIsFileStreamUrl(YesOrNoEnum.YES.getCode());
                        }
                        if (!ObjectUtils.isEmpty(e.getFileUrl()) && e.getFileUrl().contains("taskCenter")) {
                            e.setIsFileStreamUrl(YesOrNoEnum.YES.getCode());
                        }
                    });
                }
                if ("EMPTY".equals(vo.getCaseId())) {
                    vo.setCaseId(null);
                }
                vo.setIsAutoSave(caseTemporaryRecords.get(0).getIsAutoSave());
                vo.setDataSource(record.getDataSource());
                vo.setDataSourceServiceId(record.getDataSourceServiceId());

                if (!ObjectUtils.isEmpty(caseMainInfo) && CaseStatusEnum.END_CASE.getCode().equals(caseMainInfo.getCaseStatus())) {
                    //已结案将caseId置空
                    vo.setCaseId(null);
                }
            }

        }
        if (StringUtils.isEmpty(vo.getIsIndustrialTradeSpecial()) && StringUtils.isNotBlank(caseId)) {
            CaseMainDetailSimpleInfo caseMainDetailSimpleInfo = caseMainDetailSimpleInfoService.getCaseMainDetailSimpleInfo(caseId);
            if (ObjectUtil.isNotEmpty(caseMainDetailSimpleInfo)) {
                vo.setIsIndustrialTradeSpecial(caseMainDetailSimpleInfo.getIsIndustrialTradeSpecial());
            }
        }
        return vo;
    }


    /**
     * 简易处罚完成
     *
     * @return {@link boolean}
     * @author: zhengqiang
     * @date: 2022/6/15
     * @param: simpleCaseSaveFinishDto
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveCaseFinish(SimpleCaseSaveFinishDto simpleCaseSaveFinishDto) {
        LocalDateTime now = LocalDateTime.now();
        PublicSecurityDocumentNumberRollbackDTO dto = new PublicSecurityDocumentNumberRollbackDTO();
        String caseId = simpleCaseSaveFinishDto.getCaseId();
        //重新生成缴款二维码
        //getPaymentQRCodeDocument(caseId);
        try {
            //轻微违法不予处罚不用生成行为码
            String investConclusion = simpleCaseSaveFinishDto.getInvestConclusion();
            if (!Constant.STRING_2.equals(investConclusion)) {
                //生成决定书的行政行为码及缴款二维码,生成决定书文号
                createQRCodeDocument(simpleCaseSaveFinishDto, dto);
            }
            int i = dealCaseMainDetailSimpleInfo(simpleCaseSaveFinishDto);
            log.info("saveCaseFinish-i:{}", i);
            if (i > 0) {

                //保存成功,删除暂存数据
                deleteTemporaryCase();
                //数据上报处理
                dealCaseDataReport(caseId);
                //检查转处罚保存处置回传结果
                try {
                    Map<String, Object> paramMap = Collections.singletonMap("caseId", caseId);
                    PunishMainClientUtil.httpGet(PunishMainServicePortUriConstant.SEND_DISPOSAL_BACK_RESULT, paramMap);
                } catch (Exception exception) {
                    log.error("检查转处罚保存处置回传结果异常:{}", exception);
                }
                //不予处罚，在调用该方法（saveCaseFinish）对应controller层单独调用（避免不同事务出现"未找到案件信息"问题）
                if (!Constant.STRING_2.equals(investConclusion)) {
                    callBackSimpleCaseInfo(caseId);
                }
                // 进行公安委托文号报警判断
                caseDocumentRecordService.sendAlarm(dto);
                return true;
            } else {
                //数据处理异常
                //注销行政行为码
                try {
                    Map<String, String> headers = HeaderUtil.headerInfo();
                    ActsCodeRevokeDto actsCodeRevokeDto = new ActsCodeRevokeDto();
                    actsCodeRevokeDto.setBusinessUnique(caseId);
                    String param = JSON.toJSONString(actsCodeRevokeDto);
                    HttpUtil.createPost(url.concat("punish/caseActsCodeInfo/revoke")).addHeaders(headers).body(param).execute().body();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }catch (Exception e){
            caseDocumentRecordService.publicSecurityRollbackDocumentNumber(dto);
            if(e instanceof BusinessException){
                throw new BusinessException(e.getMessage());
            } else {
                throw e;
            }
        }
        return false;
    }

    /**
     * 描述：简易处罚数据回流
     *
     * @param caseId 案件id
     * @return String 错误信息
     * @author xiangyuyu
     * @date 2023/5/4
     */
    @Override
    public String callBackSimpleCaseInfo(String caseId) {
        CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(caseId);
        String dataSource = caseMainInfo.getDataSource();
        log.info("callBackSimpleCaseInfo-dataSource:{}", dataSource);
        if (!ObjectUtils.isEmpty(dataSource) && ApiVisitDataSourceEnum.isOutSystem(dataSource)) {
            ApiSimpleCaseDetailInfoCallbackDto dto = new ApiSimpleCaseDetailInfoCallbackDto(caseId, dataSource);
            //外部系统数据回流
            Result<String> callbackResult = iApiSimpleCaseDetailInfoCallbackService.callbackSimpleCaseDetailInfo(dto);
            if (HttpStatus.HTTP_OK != callbackResult.getCode()) {
                log.error("外部系统数据回流时出现异常-dataSource:" + dataSource);
            }
        }
        return null;
    }

    @Override
    public Result getEntInfoByTyxydmOfPc(String tyxydm) {
        Map<String, String> headers = HeaderUtil.headerInfo();
        EntBaseInfoDto dto = new EntBaseInfoDto();
        dto.setTyxydm(tyxydm);
        String param = JSON.toJSONString(dto);
        String response = HttpUtil.createPost(url.concat("/external/cadjjbxx/getEntInfo")).addHeaders(headers).body(param).execute().body();
        //return PunishMainClientUtil.httpPost(PunishMainServicePortUriConstant.GET_ENT_INFO_BY_ID, tyxydm);
        Result result = JSON.parseObject(response, Result.class);
        return result;
    }

    @Override
    public PoliceAdjudicationVo checkSimpleCaseParameter(SimpleCaseSaveDto saveDto) {
        if (!StrUtil.equals(saveDto.getIsPublicSecurity(), Constant.STRING_1)) {
            // 不为公安委托执法，则不需效验
            return null;
        }
        if (StrUtil.isBlank(saveDto.getClientOrgCode())) {
            throw new BusinessException("委托单位部门代码不能为空");
        }
        if (StrUtil.isBlank(saveDto.getAreaCode())) {
            throw new BusinessException("委托单位区域代码不能为空");
        }
        if (StrUtil.isBlank(saveDto.getClientLineCode())) {
            throw new BusinessException("委托单位条线编码不能为空");
        }
        if (StrUtil.isNotBlank(saveDto.getClientDeptName()) && StrUtil.isBlank(saveDto.getClientDeptCode())) {
            throw new BusinessException("缺少委托部门code");
        }
        if (StrUtil.isNotBlank(saveDto.getClientDeptCode()) && StrUtil.isBlank(saveDto.getClientDeptName())) {
            throw new BusinessException("缺少委托部门名称");
        }
        // 委托案件事项码
        if (StrUtil.isBlank(saveDto.getCatalogId())) {
            throw new BusinessException("公安委托事项内部code不能为空");
        }
        // 获得处罚维护的裁量信息
        PoliceAdjudicationVo policeAdjudication = getPoliceAdjudication(saveDto.getCatalogId());
        if (Objects.isNull(policeAdjudication)) {
            throw new BusinessException("未查询到裁量信息");
        }
        //将事项代码、记分依据维护进参数
        saveDto.setItemCode(policeAdjudication.getItemCode());
        //组装记分依据详情
        String scoringDetail = assembleScoringDetail(policeAdjudication);
        saveDto.setScoringBasis(scoringDetail);
        // 计分依据不为空 && 扣分标准为空
        if (StrUtil.isNotBlank(policeAdjudication.getScoringBasis()) && StrUtil.isBlank(saveDto.getLicenseScore())) {
            throw new BusinessException("该公安委托事项必须记分");
        }
        // 计分依据不为空 && 扣分标准不为空 && 前端传递的扣分标准与配置的扣分标准不相同
        if (StrUtil.isNotBlank(policeAdjudication.getScoringBasis()) && Objects.nonNull(policeAdjudication.getLicenseScore())
                && !Objects.equals(Integer.valueOf(saveDto.getLicenseScore()), policeAdjudication.getLicenseScore())){
            throw new BusinessException("扣分标准与公安裁量配置不匹配！");
        }
        if (StrUtil.isNotBlank(saveDto.getLicenseNumber()) &&
                (saveDto.getLicenseNumber().length() < 5 || saveDto.getLicenseNumber().length() > 18)) {
            throw new BusinessException("驾驶证编号只能输入5-18位");
        }
        if (StrUtil.isNotBlank(saveDto.getLicenseFileNumber()) &&
                saveDto.getLicenseFileNumber().length() != 12) {
            throw new BusinessException("驾驶证档案编号长度只能为12位");
        }
        if (StrUtil.isNotBlank(saveDto.getLicenceDepartment()) &&
                saveDto.getLicenceDepartment().length() > 50) {
            throw new BusinessException("发证机关最多输入50位");
        }
        if (!hasSurplusNumber(saveDto.getClientOrgCode())) {
            throw new BusinessException("处罚决定书编号号段已用完，请联系部门管理员分配新号段");
        }
        SysDepartParam sysDepartParam = sysDepartParamService.getPublicSecurityEntrustSysDepartParamByOrgCodeAndDeptCode(saveDto.getClientOrgCode(),
                StrUtil.isBlank(saveDto.getClientDeptCode()) ? saveDto.getClientOrgCode() : saveDto.getClientDeptCode());
        if (StrUtil.isBlank(sysDepartParam.getSignUrl())) {
            throw new BusinessException("该委托部门未配置签章，请联系部门管理员配置签章");
        }
        return policeAdjudication;
    }

    /**
     * 组装记分依据详情
     * @param policeAdjudication
     * @return
     */
    private String assembleScoringDetail(PoliceAdjudicationVo policeAdjudication) {
        // 计分依据
        String scoringBasis = StrUtil.isNotBlank(policeAdjudication.getScoringBasis()) ? policeAdjudication.getScoringBasis() : "";
        // 计分依据条号
        String scoringArticleNumber = StrUtil.isNotBlank(policeAdjudication.getScoringArticleNumber()) ? policeAdjudication.getScoringArticleNumber() : "";
        // 计分依据款号
        String scoringStyleNumber = StrUtil.isNotBlank(policeAdjudication.getScoringStyleNumber()) ? policeAdjudication.getScoringStyleNumber() : "";
        // 计分依据项号
        String scoringItemNumber = StrUtil.isNotBlank(policeAdjudication.getScoringItemNumber()) ? policeAdjudication.getScoringItemNumber() : "";
        // 拼接记分依据详情
        String scoringDetail = scoringBasis + scoringArticleNumber + scoringStyleNumber + scoringItemNumber;
        return scoringDetail;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean transferCaseToRecord(SimpleCaseSaveDto saveDto) {
        if (!StrUtil.equals(saveDto.getIsPublicSecurity(), Constant.STRING_1)) {
            // 不为公安委托执法，则不需要移交
            return false;
        }
        if (Objects.isNull(saveDto.getHasDrivingLicence()) || Objects.isNull(saveDto.getHasLicensePlate())) {
            throw new BusinessException("公安委托执法时是否无牌或是否无证不能为空");
        }
        if (!Constant.STRING_1.equals(saveDto.getHasDrivingLicence())
                && !Constant.STRING_1.equals(saveDto.getHasLicensePlate())) {
            //有牌 且 有证 则不需要移交
            return false;
        }
        if (StrUtil.isBlank(saveDto.getPartyType())) {
            throw new BusinessException("当事人类型不能为空");
        }
        if (StrUtil.isEmpty(saveDto.getTransferRemark())) {
            throw new BusinessException("移交记录不能为空");
        }
        caseSimpleTransferRecordService.insert(convertToTransferRecord(saveDto));
        //移交后清空暂存记录
        deleteTemporaryCase();
        return true;
    }

    /**
     * 转换简易程序保存参数 到移交记录对象
     *
     * @param saveDto 简易程序保存参数
     * @return 移交记录对象
     */
    private CaseSimpleTransferRecord convertToTransferRecord(SimpleCaseSaveDto saveDto) {
        UserDTO user = getUser();
        CaseSimpleTransferRecord transferRecord = new CaseSimpleTransferRecord();
        transferRecord.setId(com.icinfo.framework.tools.utils.StringUtils.uuid());
        transferRecord.setItemName(saveDto.getCaseReasonName());
        // 获得处罚维护的裁量信息
        PoliceAdjudicationVo policeAdjudication = getPoliceAdjudication(saveDto.getCatalogId());
        transferRecord.setItemCode(policeAdjudication.getItemCode());
        transferRecord.setHasLicensePlate(saveDto.getHasLicensePlate());
        transferRecord.setHasDrivingLicence(saveDto.getHasDrivingLicence());
        transferRecord.setPartyType(saveDto.getPartyType());
        transferRecord.setPartyName(getByPartyType(saveDto.getPartyType(), saveDto.getName(), saveDto.getEntName()));
        transferRecord.setUniscid(saveDto.getUniscid());
        transferRecord.setLegalName(saveDto.getLegal());
        transferRecord.setCertType(getByPartyType(saveDto.getPartyType(), saveDto.getCertType(), saveDto.getLegalCertType()));
        transferRecord.setCertCode(getByPartyType(saveDto.getPartyType(), saveDto.getCertNo(), saveDto.getLegalCertNo()));
        transferRecord.setAddress(getByPartyType(saveDto.getPartyType(), saveDto.getAddress(), saveDto.getUnitAddress()));
        transferRecord.setMobile(getByPartyType(saveDto.getPartyType(), saveDto.getMobile(), saveDto.getPhone()));
        transferRecord.setSex(saveDto.getSex());
        transferRecord.setAge(saveDto.getAge());
        transferRecord.setWorkUnit(saveDto.getUnitName());
        transferRecord.setEntType(saveDto.getEntType());
        transferRecord.setJob(saveDto.getJob());
        transferRecord.setBusinessAddress(saveDto.getBusinessAddress());
        transferRecord.setEntrustOrgCode(saveDto.getClientOrgCode());
        transferRecord.setEntrustDeptCode(saveDto.getClientDeptCode());
        transferRecord.setHandleAreaCode(user.getAreaCode());
        transferRecord.setHandleOrgCode(user.getOrgCode());
        transferRecord.setHandleDeptCode(user.getDeptCode());
        //处理办案人员
        for (CaseHandlePersonInfoDto caseHandlePersonInfoDto : saveDto.getHandlePersonInfoList()) {
            if (Constant.STRING_1.equals(caseHandlePersonInfoDto.getHandlePersonType())) {
                transferRecord.setMainHandlePerson(caseHandlePersonInfoDto.getHandlePersonName());
                transferRecord.setMainHandlePersonId(caseHandlePersonInfoDto.getHandlePersonId());
            } else {
                transferRecord.setAssistHandlePerson(caseHandlePersonInfoDto.getHandlePersonName());
                transferRecord.setAssistHandlePersonId(caseHandlePersonInfoDto.getHandlePersonId());
            }
        }
        transferRecord.setTransferRemark(saveDto.getTransferRemark());
        transferRecord.setHappenAddress(saveDto.getCaseHappenAddressDetail());
        transferRecord.setHappenTime(DateUtil.parse(saveDto.getCaseHappenTime(), "yyyy-M-d HH:mm"));
        transferRecord.setCaseReactionContent(saveDto.getCaseReactionContent());
        transferRecord.setCaseRemark(saveDto.getCaseRemark());
        transferRecord.setEvidenceUrl(JSON.toJSONString(saveDto.getCaseEvidencePhotoList()));
        transferRecord.setCreateTime(new Date());
        transferRecord.setCreateUser(String.valueOf(user.getUserId()));
        return transferRecord;
    }

    /**
     * 根据当事人类型取不同字段
     *
     * @param partyType 当事人类型
     * @param personStr 个人描述
     * @param entStr    企业描述
     * @return 描述
     */
    private String getByPartyType(String partyType, String personStr, String entStr) {
        return PartyTypeEnum.PERSON.getCode().equals(partyType) ? personStr : entStr;
    }

    public void verifyDiscretionAmount(SimpleCaseSaveDto saveDto, PoliceAdjudicationVo policeAdjudicationVo){
        // 违法情节为空 或 没有进行罚款 则不需要进行判断
        if (StrUtil.isBlank(saveDto.getIllegalSituation()) || !saveDto.getPunishKinds().contains(PunishKindsEnum.PunishKind_2.getDes())){
            return;
        }
        // 存在公安裁量，且有罚款标准则不需要判断自由裁量的罚款金额
        if (Objects.nonNull(policeAdjudicationVo) && StrUtil.isNotBlank(policeAdjudicationVo.getDiscretionaryBasis())){
            return;
        }
        CompareSingleDiscretionDto dto = new CompareSingleDiscretionDto(saveDto.getIllegalSituation(), saveDto.getDraftPunishMoney());
        Map<String, String> headers = HeaderUtil.headerInfo();
        String response = HttpUtil.createGet(url.concat("/punish/config/discretion/verifyDiscretionAmount")).addHeaders(headers).form(BeanUtil.beanToMap(dto)).execute().body();
        Result result = JSON.parseObject(response, Result.class);
        if (Constant.INTEGER_200 != result.getCode()){
            throw new BusinessException(result.getMessage());
        }
    }

    /**
     * 检查是否有余号
     * @param areCode
     * @return
     */
    public Boolean hasSurplusNumber(String areCode) {
        Map<String, String> headers = HeaderUtil.headerInfo();
        Map<String, Object> urlParam = new HashMap<>(1);
        urlParam.put("orgCode", areCode);
        String response = HttpUtil.createGet(url.concat("/punish/common/publicSecurityEntrustDocumentNumber/hasSurplusNumber")).addHeaders(headers).form(urlParam).execute().body();
        Result result = JSON.parseObject(response, Result.class);
        if (Objects.equals(result.getCode(), 200)) {
            return (Boolean) result.getData();
        }
        log.error("公安委托简单案件->余号查询失败！");
        throw new BusinessException("公安委托简单案件->余号查询失败！");
    }


    public PoliceAdjudicationVo getPoliceAdjudication(String publicSecurityItemCode) {
        Map<String, String> headers = HeaderUtil.headerInfo();
        Map<String, Object> urlParam = new HashMap<>(1);
        urlParam.put("itemRelationCode", publicSecurityItemCode);
        String response = HttpUtil.createGet(url.concat("/punish/config/policeAdjudication/getByItemRelationCode")).addHeaders(headers).form(urlParam).execute().body();
        Result result = JSON.parseObject(response, Result.class);
        if (Objects.equals(result.getCode(), 200)) {

            return JSONObject.parseObject(String.valueOf(result.getData()), PoliceAdjudicationVo.class);
        }
        log.error("公安委托简单案件->获取事项裁定信息失败！");
        throw new BusinessException("获取事项裁定信息失败");
    }

    /**
     * 描述：处理简易案件信息
     *
     * @param simpleCaseSaveFinishDto 简单的案例保存完成dto
     * @return int
     * @author shishengyao
     * @date 2022/11/22
     */
    private int dealCaseMainDetailSimpleInfo(SimpleCaseSaveFinishDto simpleCaseSaveFinishDto) {
        LocalDateTime now = LocalDateTime.now();
        String caseId = simpleCaseSaveFinishDto.getCaseId();
        //决定书文号
        String documentNumber = simpleCaseSaveFinishDto.getDocumentNumber();
        CaseMainDetailSimpleInfo caseMainDetailSimpleInfo = caseMainDetailSimpleInfoService.getCaseMainDetailSimpleInfo(caseId);
        String punishKinds = caseMainDetailSimpleInfo.getPunishKinds();
        //更新简易程序详情表
        CaseMainDetailSimpleInfo updateSimpleInfo = new CaseMainDetailSimpleInfo();
        updateSimpleInfo.setId(caseMainDetailSimpleInfo.getId());
        updateSimpleInfo.setCaseId(caseMainDetailSimpleInfo.getCaseId());
        updateSimpleInfo.setNotSignReason(simpleCaseSaveFinishDto.getNotSignReason());
        updateSimpleInfo.setNotSignReasonReplenish(simpleCaseSaveFinishDto.getNotSignOtherReason());
        updateSimpleInfo.setPunishDocumentNumber(documentNumber);

        //更新主表结案相关信息
        CaseMainInfo updateCaseMainInfo = new CaseMainInfo();
        updateCaseMainInfo.setId(caseId);
        //更新主表结案相关信息
        updateCaseMainInfo.setId(caseId);
        updateCaseMainInfo.setCaseRegistTime(now);
        //裁决完毕日期
        updateCaseMainInfo.setCaseVerdictEndTime(now);
        if (ObjectUtil.isNotEmpty(punishKinds) && punishKinds.contains("罚款")) {
            //有罚款，进入执行阶段
            updateCaseMainInfo.setCaseStatus(CaseStatusEnum.HANDLING_CASE.getCode());
            updateCaseMainInfo.setCaseCurrentStageCode("PUNISH_EXECUTION");
            updateCaseMainInfo.setCaseCurrentStageName("处罚执行");
            updateCaseMainInfo.setCaseCurrentLinkCode("LINK-202203020950");
            updateCaseMainInfo.setCaseCurrentLinkName("处罚执行");

        } else {
            // 没有罚款，直接结案
            updateCaseMainInfo.setCaseStatus(CaseStatusEnum.END_CASE.getCode());
            updateCaseMainInfo.setCaseEndTime(now);
            updateCaseMainInfo.setCaseCurrentStageCode("CLOSE_ARCHIVING");
            updateCaseMainInfo.setCaseCurrentStageName("结案");
            updateCaseMainInfo.setCaseCurrentLinkCode("LINK-202203020953");
            updateCaseMainInfo.setCaseCurrentLinkName("归档");
            //更新简易程序信息表
            if (!ObjectUtils.isEmpty(caseMainDetailSimpleInfo)) {
                updateSimpleInfo.setExecuteWay("自觉履行");
                updateSimpleInfo.setExecuteFinishDate(LocalDate.now());
            }
        }
        //更新简易程序详情表
        caseMainDetailSimpleInfoMapper.updateByPrimaryKeySelective(updateSimpleInfo);
        if (ObjectUtil.isNotEmpty(documentNumber)) {
            //更新补充表数据
            Example example = new Example(CaseMainDetailAuxiliaryInfo.class);
            example.createCriteria().andEqualTo("caseId", caseId);
            List<CaseMainDetailAuxiliaryInfo> caseMainDetailAuxiliaryInfos = caseMainDetailAuxiliaryInfoMapper.selectByExample(example);
            if (!ObjectUtils.isEmpty(caseMainDetailAuxiliaryInfos)) {
                for (CaseMainDetailAuxiliaryInfo caseMainDetailAuxiliaryInfo : caseMainDetailAuxiliaryInfos) {
                    CaseMainDetailAuxiliaryInfo updateCaseMainDetailAuxiliaryInfo = new CaseMainDetailAuxiliaryInfo();
                    updateCaseMainDetailAuxiliaryInfo.setId(caseMainDetailAuxiliaryInfo.getId());
                    updateCaseMainDetailAuxiliaryInfo.setPunishDocumentNumber(documentNumber);
                    caseMainDetailAuxiliaryInfoMapper.updateByPrimaryKeySelective(updateCaseMainDetailAuxiliaryInfo);
                }
            }
            //更新案件编号
            updateCaseMainInfo.setCaseNumber(documentNumber);
        }
        return caseMainInfoMapper.updateByPrimaryKeySelective(updateCaseMainInfo);
    }

    /**
     * 人社base阶段数据上报单独处理
     *
     * @param caseId
     */
    private void dealCaseDataReport(String caseId) {
        //人社的简易处罚, 调用推送数据上报接口 todo 后续可优化成全条线
        CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(caseId);
        if (TerritoryCodeEnum.RLSB.getCode().equals(caseMainInfo.getCaseTerritoryCode())) {
            CollectReportDataDto reportDataDto = new CollectReportDataDto();
            reportDataDto.setCaseId(caseId);
            reportDataDto.setCasePartyType(Constant.STRING_1);
            reportDataDto.setCaseTerritoryCode(TerritoryCodeEnum.RLSB.getCode());
            try {
                log.info("推送数据上报案件信息请求参数: {}", reportDataDto);
                Result result = PunishMainClientUtil.httpPost(PunishMainServicePortUriConstant.COLLECT_REPORT_DATA, reportDataDto);
                log.info("推送数据上报案件信息返回信息: {}", result);
            } catch (Exception exception) {
                //保存上报异常数据
                DataReportSaveFailRecordOfApp dataReportSaveFailRecord = new DataReportSaveFailRecordOfApp();
                dataReportSaveFailRecord.setCaseId(caseId);
                dataReportSaveFailRecord.setCasePartyType(Constant.STRING_1);
                dataReportSaveFailRecord.setCaseTerritoryCode(TerritoryCodeEnum.RLSB.getCode());
                dataReportSaveFailRecord.setId(UUID.fastUUID().toString(true));
                dataReportSaveFailRecord.setCreateTime(new Date());
                dataReportSaveFailRecord.setFailReason("app服务--案件上报数据保存异常:" + exception.toString());
                dataReportSaveFailRecordMapper.insert(dataReportSaveFailRecord);
                log.info("推送数据上报案件信息异常: {}", exception);
            }
        }
    }

    /**
     * 描述： 简易处罚暂存功能
     *
     * @return {@link int}
     * @author: zhengqiang
     * @date: 2022/6/21
     * @param: saveDto
     **/
    @Override
    public int saveTemporary(SimpleCaseSaveDto saveDto) {
        UserDTO userInfo = UserUtil.getUserInfo();
        //查询是否存在暂存记录
        Example queryExample = new Example(CaseTemporaryRecord.class);
        queryExample.createCriteria().andEqualTo("addUser", userInfo.getLoginName())
                .andEqualTo("caseId", "EMPTY").andEqualTo("orgCode", userInfo.getOrgCode());

        CaseTemporaryRecord record = new CaseTemporaryRecord();
        record.setContent(JSONObject.toJSONString(saveDto));
        record.setCreateTime(LocalDateTime.now());
        String dataSourceServiceId = saveDto.getDataSourceServiceId();
        record.setDataSourceServiceId(dataSourceServiceId);
        record.setDataSource(saveDto.getCaseSourceAppId());
        List<CaseTemporaryRecord> caseTemporaryRecords = caseTemporaryRecordMapper.selectByExample(queryExample);
        String extraJsonInfo = saveDto.getExtraJsonInfo();
        String dataSource = null;
        if (!ObjectUtils.isEmpty(extraJsonInfo) && !ApiVisitDataSourceEnum.TASKCENTER.getCode().equals(saveDto.getCaseSourceAppId())) {
            JSONObject jsonObject = JSONObject.parseObject(extraJsonInfo);
            Object dataSourceObj = jsonObject.get("dataSource");
            if (ObjectUtils.isEmpty(dataSourceObj)) {
                throw new BusinessException("未指定数据来源");
            }
            dataSource = (String) dataSourceObj;
            if (ApiVisitDataSourceEnum.isOutSystem(dataSource)) {
                record.setDataSource(dataSource);
            }
        }
        //应用接入数据处理
        if (!ObjectUtils.isEmpty(saveDto.getCaseSourceAppId())) {
            if (!ObjectUtils.isEmpty(saveDto.getDataSourceServiceId())) {
                record.setDataSourceServiceId(saveDto.getDataSourceServiceId());
            }
            record.setDataSource(saveDto.getCaseSourceAppId());
        }
        if (!ObjectUtils.isEmpty(caseTemporaryRecords)) {
            CaseTemporaryRecord tmpRecord = caseTemporaryRecords.get(Constant.INTEGER_0);
            if (!ObjectUtils.isEmpty(tmpRecord)) {
                if (!ObjectUtil.isEmpty(tmpRecord.getDataSource())) {
                    //外部系统录入，暂存，回首页，进入简易处罚录入，暂存，数据会丢失，在丢失前进行赋值
                    if (ObjectUtils.isEmpty(dataSourceServiceId)) {
                        //当前案件暂存，同时不是第一次缓存
                        if (!YesOrNoEnum.YES.getCode().equals(saveDto.getIsFirstCache())) {
                            record.setDataSourceServiceId(tmpRecord.getDataSourceServiceId());
                        }
                    }
                    record.setDataSource(tmpRecord.getDataSource());
                    JSONObject oriContent = JSONObject.parseObject(tmpRecord.getContent());
                    //拿到主办人员手机号码
                    SimpleCaseSaveDto tempDto = JSONObject.toJavaObject(oriContent, SimpleCaseSaveDto.class);
                    List<CaseHandlePersonInfoDto> oriHandlePersonInfoList = tempDto.getHandlePersonInfoList();
                    List<CaseHandlePersonInfoDto> newHandlePersonInfoList = saveDto.getHandlePersonInfoList();
                    if (!ObjectUtils.isEmpty(oriHandlePersonInfoList)) {
                        oriHandlePersonInfoList.forEach(e -> {
                            if (HandlePersonTypeEnum.MAIN.getCode().equals(e.getHandlePersonType())) {
                                newHandlePersonInfoList.forEach(newE -> {
                                    if (newE.getHandlePersonType().equals(e.getHandlePersonType())) {
                                        newE.setHandlePersonTel(e.getHandlePersonTel());
                                        newE.setHandleOrgCode(e.getHandleOrgCode());
                                        return;
                                    }
                                });
                            }
                        });
                    }
                    saveDto.setHandlePersonInfoList(newHandlePersonInfoList);
                    record.setContent(JSONObject.toJSONString(saveDto));
                }
            }
            if (!ObjectUtils.isEmpty(saveDto.getCaseId())) {
                //更新简易处罚详情表的录入内容字段
                CaseMainDetailSimpleInfo caseMainDetailSimpleInfo = caseMainDetailSimpleInfoService.getCaseMainDetailSimpleInfo(saveDto.getCaseId());
                if (!ObjectUtils.isEmpty(caseMainDetailSimpleInfo)) {
                    if (StringUtils.isNotBlank(saveDto.getIsIndustrialTradeSpecial())) {
                        caseMainDetailSimpleInfo.setIsIndustrialTradeSpecial(saveDto.getIsIndustrialTradeSpecial());
                    }
                    caseMainDetailSimpleInfo.setCaseContent(JSONObject.toJSONString(saveDto));
                    caseMainDetailSimpleInfoMapper.updateByPrimaryKey(caseMainDetailSimpleInfo);
                }
                //案件不存在,设置暂存中caseId为空
                CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(saveDto.getCaseId());
                if (ObjectUtils.isEmpty(caseMainInfo)) {
                    saveDto.setCaseId(null);
                    record.setContent(JSONObject.toJSONString(saveDto));
                }

            }

            //更新暂存表内容
            if (!YesOrNoEnum.NO.getCode().equals(record.getIsAutoSave())) {
                //原来是自动保存则更新是否自动保存状态
                if (record.getIsAutoSave() == null) {
                    record.setIsAutoSave(YesOrNoEnum.NO.getCode());
                } else {
                    record.setIsAutoSave(saveDto.getIsAutoSave());
                }

            }
            return caseTemporaryRecordMapper.updateByExampleSelective(record, queryExample);

        } else {
            //新增暂存
            record.setId(BaseUtil.createUid());
            //设置为EMPTY
            record.setCaseId("EMPTY");
            record.setAddUser(userInfo.getLoginName());
            record.setOrgCode(userInfo.getOrgCode());
            record.setCreateTime(LocalDateTime.now());
            record.setIsAutoSave(saveDto.getIsAutoSave());
            return caseTemporaryRecordMapper.insertSelective(record);
        }

    }

    /**
     * 根据统一信用代码获取企业信息
     *
     * @param tyxydm
     * @return {@link Map< String, Object>}
     * @author liyafeng
     * @date 2022/7/1
     */
    @Override
    public JSONObject getEntInfoByTyxydm(String tyxydm) {
        JSONObject entJSONObject = new JSONObject();
        String url = "http://59.202.52.139:8082/frk/api/getqyjbxx";
        Map<String, String> map = new HashMap<>(4);
        map.put("tyxydm", tyxydm);
        String response = BaseUtil.sendGETRequest(url, map);
        JSONObject jsonObject = JSONObject.parseObject(response);
        if (jsonObject.getString("code").equals("00")) {
            JSONArray array = jsonObject.getJSONArray("result");
            if (null != array && array.size() > 0) {
                entJSONObject = array.getJSONObject(0);
            }
        }
        return entJSONObject;
    }


    /**
     * 通过身份证获取用户具体信息
     *
     * @param idCardObj
     * @return
     */
    @Override
    public Result getPersonInfoByIdCard(JSONObject idCardObj) {
        return PunishMainClientUtil.httpPost(PunishMainServicePortUriConstant.GET_PERSON_INFO_BY_ID_CARD, idCardObj);
    }

    /**
     * 获取有执法证协办人员列表
     *
     * @return
     */
    @Override
    public Result<List<HandleAssistVo>> getAssistHandleList() {
        return PunishMainClientUtil.httpPost(PunishMainServicePortUriConstant.GET_ASSIST_HANDLE_LIST, null);
    }


    /**
     * 描述： 获取历史最近3个办案人员
     *
     * @return {@link Result< List< HandleAssistVo>>}
     * @author: zhengqiang
     * @date: 2022/8/27
     **/
    @Override
    public Result<List<HandleAssistVo>> getHisAssistHandleList(HisAssistHandleRequest request) {
        UserDTO userInfo = UserUtil.getUserInfo();
        List<HandleAssistVo> handleAssistVoList = new ArrayList<>();
        if (Constant.STRING_1.equals(request.getSourceType()) || Constant.STRING_3.equals(request.getSourceType())) {
            //简易处罚
            handleAssistVoList = caseHandlePersonRecordMapper.getHisAssistHandleListByCaseType(userInfo.getUserId().toString(), userInfo.getOrgCode(), request.getSourceType());

        } else if (Constant.STRING_2.equals(request.getSourceType())) {
            //办案直通车
            handleAssistVoList = caseHandlePersonRecordMapper.getHisAssistHandleListOfZtc(userInfo.getUserId().toString(), userInfo.getOrgCode());
        }
        return Result.success(Constant.STRING_SUCCESS_EN, handleAssistVoList);
    }

    /**
     * 【V1.4.1】描述： 根据名称搜索机构用户
     *
     * @return {@link Result}
     * @author: zhengqiang
     * @date: 2022/8/27
     * @param: userName
     **/
    @Override
    public Result<List<HandleAssistVo>> searchOrgUserListByName(String userName) {
        Map urlParam = Collections.singletonMap("userName", userName);
        return PunishMainClientUtil.httpGet(PunishMainServicePortUriConstant.SEARCH_ORG_USER_LIST_BY_NAME, urlParam);
    }

    /**
     * 描述：生成行政行为码及缴款二维码简易处罚文书,生成文书编号
     *
     * @author zhengqiang
     * @date 2023/02/15
     */
    public void createQRCodeDocument(SimpleCaseSaveFinishDto simpleCaseSaveFinishDto, PublicSecurityDocumentNumberRollbackDTO dto) {
        // 公安委托文号回滚标识,默认不需要回滚
        dto.setRollback(Boolean.FALSE);
        String caseId = simpleCaseSaveFinishDto.getCaseId();
        //查询行政行为码是否已经生成
        CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(caseId);
        /*String caseQrCodeUrl = caseMainInfo.getCaseQrCodeUrl();
        String caseBarCodeUrl = caseMainInfo.getCaseBarCodeUrl();
        if (ObjectUtils.isEmpty(caseQrCodeUrl) && ObjectUtils.isEmpty(caseBarCodeUrl)) {
            //生成行政行为码
            Map<String, String> codeMap = ((SimpleCaseServiceImpl) AopContext.currentProxy()).getCaseQRCode(caseId);
            if (ObjectUtil.isNotEmpty(codeMap)) {
                caseQrCodeUrl = codeMap.get("caseQrCodeUrl");
                caseBarCodeUrl = codeMap.get("caseBarCodeUrl");
            }
        }*/
        String kindCode = getKindCodeByCaseId(caseId);

        //查询简易处罚文书列表
        CaseDocumentRecordDto caseDocumentRecord = caseDocumentRecordMapper.selectCaseDocumentRecordByKindCode(caseId, kindCode);
        if (ObjectUtil.isEmpty(caseDocumentRecord)) {
            //不予处罚是不生成文书的
            return;
        }
        //String qrBase64 = null;
        String qrUrl = null;
        String XZCFJDS_JKDH = null;
        String documentNumber = caseDocumentRecord.getDocumentNumber();
        //简易处罚,查询缴款方式
        CaseMainDetailSimpleInfo simpleInfo = caseMainDetailSimpleInfoService.getCaseMainDetailSimpleInfo(caseId);
        JSONObject contentObject = JSONObject.parseObject(simpleInfo.getCaseContent());
        // 得到委托执法的clientOrgCode
        String clientOrgCode = contentObject.getString("clientOrgCode");
        //未签字确认，重新生成文书
        if (ObjectUtil.isNotEmpty(caseDocumentRecord) && ObjectUtil.isEmpty(caseDocumentRecord.getDocumentUrlAfterSign())) {
            if (PayWayEnum.OFF_SITE.getCode().equals(simpleInfo.getPayWay())
                    && simpleInfo.getPunishKinds().contains("罚款")
                    && !DocumentKindEnum.DOC_KIND_JYCXGAWTCFJDS.getCode().equals(kindCode)) {
                // 生成并获取缴费单号
                CasePaymentSlipNumberSaveDto slipNumberSaveDto = new CasePaymentSlipNumberSaveDto();
                slipNumberSaveDto.setCaseId(caseDocumentRecord.getCaseId());
                slipNumberSaveDto.setDocumentCatalogCode(caseDocumentRecord.getDocumentCatalogCode());
                slipNumberSaveDto.setCaseType(CaseTypeEnum.SIMPLE_PROCEDURE.getCode());
                slipNumberSaveDto.setPartyId(caseDocumentRecord.getPartyId());
                Result result = PunishMainClientUtil.httpPost(PunishMainServicePortUriConstant.SAVE_CASE_PAYMENT_MAIN_RECORD, slipNumberSaveDto);
                Map<String, Object> record = JSONObject.parseObject(result.getData().toString(), Map.class);
                System.out.println("支付信息返回=======" + record.toString());
                qrUrl = record.get("qrBase64").toString();
                XZCFJDS_JKDH = record.get("paymentSlipNumber").toString();
                //paramMap.put("XZCFJDS_JKDH", paymentSlipNumber);
                //base64优化成地址
                //qrUrl = record.get("qrUrl").toString();

            }
            //重新生成文书
            JSONObject jsonObject = JSON.parseObject(caseDocumentRecord.getDocumentContent());
            //生成文号
            if (ObjectUtils.isEmpty(documentNumber)) {
                if (DocumentKindEnum.DOC_KIND_JYCXGAWTCFJDS.getCode().equals(kindCode)) {
                    // 进行公安文号委托后续报错需要文号回滚
                    documentNumber = caseDocumentRecordService.getPublicSecurityDocumentNumber(clientOrgCode);
                    dto.setDocumentNumber(documentNumber);
                    dto.setOrgCode(clientOrgCode);
                    dto.setRollback(Boolean.TRUE);
                } else {
                    //获取文号
                    documentNumber = caseDocumentRecordService.getCommonDocumentNumber(caseId, caseDocumentRecord.getDocumentCatalogCode());
                }
            }
            //设置文号
            jsonObject.put("documentNumber", documentNumber);
            //设置行政行为码
           /* jsonObject.put("qrCodeUrl", caseQrCodeUrl);
            jsonObject.put("barCodeUrl", caseBarCodeUrl);*/
            //设置缴款二维码
            //List payInfoList= new ArrayList();
            if (!ObjectUtils.isEmpty(qrUrl)) {
                //SysDepartParam sysDepartParam= sysDepartParamService.getSysDepartParamByOrgCodeAndDeptCode(caseMainInfo.getCaseOrgCode(), caseMainInfo.getCaseDeptCode());
                jsonObject.put("qrBase64", qrUrl);
                jsonObject.put("XZCFJDS_JKDH", XZCFJDS_JKDH);
                /*Map<String,String>  payInfoMap= new HashMap<>(2);
                payInfoMap.put("XZCFJDS_JKDH", XZCFJDS_JKDH);
                payInfoMap.put("qrBase64", qrUrl);
                payInfoMap.put("XZCFJDS_JNFKD",sysDepartParam.getPayBankName());
                payInfoMap.put("XZCFJDS_SKZH","（户名："+sysDepartParam.getPayBankAccountName()+"，账号："+sysDepartParam.getPayBankAccount()+"）");
                payInfoList.add(payInfoMap);*/
                //jsonObject.put("punishKindCheckPayInfo", payInfoList);
            }
            // 重新生成文书
            FillAndConvertToPdfRequest pdfRequest = new FillAndConvertToPdfRequest();
            HashMap<String, Object> jsonMap = new HashMap<>(64);
            for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
                jsonMap.put(entry.getKey(), entry.getValue());
            }
            //jsonMap.put("punishKindCheckPayInfo", payInfoList);
            pdfRequest.setTemplateCode(caseDocumentRecord.getDocumentTemplateCode());
            pdfRequest.setParamMap(jsonMap);
            Map<String, String> unSealPdfUrl = appCaseBeforeDocumentRecordService.getConvertedPdfUrl(pdfRequest);
            ConfigBusiParamDocumentInfo detailByDocumentCatalogCode = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(caseDocumentRecord.getDocumentCatalogCode());
            //判断是否需要签章
            String pdfSealUrl = "";
            log.info("++++++++++++++++++判断是否签章开始");
            if (YesOrNoEnum.YES.getCode().equals(detailByDocumentCatalogCode.getIsDeptSign())) {
                // 签字捺印
                FileSealInfoQueryDto queryDto = new FileSealInfoQueryDto();
                String entrustClientOrgCode = getEntrustClientOrgCodeIfExists(caseId, caseMainInfo);
                if (StringUtils.isNotEmpty(entrustClientOrgCode)) {
                    SysDepartParam sysDepartParam = sysDepartParamService.getSysDepartParamByOrgCodeAndDeptCode(entrustClientOrgCode, null);
                    log.info("+++++++++++++++++有结果unicode:{}", sysDepartParam.getUnicode());
                    queryDto.setUniscid(sysDepartParam.getUnicode());
                    queryDto.setDeptCode(null);
                } else {
                    SysDepartParam sysDepartParam = sysDepartParamService.getSysDepartParamByOrgCodeAndDeptCode(caseMainInfo.getCaseOrgCode(), caseMainInfo.getCaseDeptCode());
                    queryDto.setUniscid(sysDepartParam.getUnicode());
                    queryDto.setDeptCode(caseMainInfo.getCaseDeptCode());
                }
                queryDto.setFileBase64(unSealPdfUrl.get("fileBase64"));
                pdfSealUrl = appCaseBeforeDocumentRecordService.dealFileSeal(queryDto);
            }
            if (DocumentKindEnum.DOC_KIND_JYCXGAWTCFJDS.getCode().equals(kindCode)) {
                pdfSealUrl = unSealPdfUrl.get("fileUrl");
            }
            // 返回
            Map<String, Object> resultMap = new HashMap<>(16);
            resultMap.put("success", "true");
            resultMap.put("pdfSealUrl", pdfSealUrl);
            caseDocumentRecord.setDocumentUrlAfterSeal(pdfSealUrl);
            caseDocumentRecord.setDocumentContent(jsonObject.toJSONString());
            caseDocumentRecord.setDocumentNumber(documentNumber);
            caseDocumentRecordMapper.updateByPrimaryKeySelective(caseDocumentRecord);

        }
        //设置文号
        simpleCaseSaveFinishDto.setDocumentNumber(documentNumber);

    }

    private String getKindCodeByCaseId(String caseId) {
        CaseMainDetailSimpleInfo simpleInfo = caseMainDetailSimpleInfoService.getCaseMainDetailSimpleInfo(caseId);
        JSONObject jsonObject = JSONObject.parseObject(simpleInfo.getCaseContent());
        String isPublicSecurity = jsonObject.getString("isPublicSecurity");
        if (StrUtil.equals(isPublicSecurity, "1")) {
            // 如果是公安委托执法 则生成公安委托执法对应的文书
            return DocumentKindEnum.DOC_KIND_JYCXGAWTCFJDS.getCode();
        } else {
            return DocumentKindEnum.DOC_KIND_JYCXCFJDS.getCode();
        }
    }

    private String getEntrustClientOrgCodeIfExists(String caseId, CaseMainInfo caseMainInfo) {
        Example caseReasonMainRecordExample = new Example(CaseReasonMainRecord.class);
        caseReasonMainRecordExample.createCriteria().andEqualTo("caseId", caseId).andEqualTo("sxType", "4");
        List<CaseReasonMainRecord> caseReasonMainRecords = caseReasonMainRecordMapper.selectByExample(caseReasonMainRecordExample);
        //当简易程序 && 有委托执法事项时，取委托单位的组织code查询
        if (CaseTypeEnum.SIMPLE_PROCEDURE.getCode().equals(caseMainInfo.getCaseType()) && CollUtil.isNotEmpty(caseReasonMainRecords)) {
            log.info("+++++++++++++++有委托");
            CaseReasonMainRecord caseReasonMainRecord = caseReasonMainRecords.get(Constant.INTEGER_0);
            return caseReasonMainRecord.getClientOrgCode();
        }
        log.info("+++++++++++++++没有查到委托");
        return null;
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    @Override
    public Map<String, String> getCaseQRCode(String caseId) {
        Map<String, String> result = new HashMap<>();
        //生成行政行为码
        try {
            //调用生成行政行为码
            Map<String, String> headers = HeaderUtil.headerInfo();
            ActsCodeDto actsCodeDto = new ActsCodeDto();
            actsCodeDto.setCaseId(caseId);
            String param = JSON.toJSONString(actsCodeDto);
            HttpUtil.createPost(url.concat("punish/caseActsCodeInfo/saveCaseActsCodeInfo")).addHeaders(headers).body(param).execute().body();
            //重新查询行政行为码
            CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(caseId);
            result.put("caseQrCodeUrl", caseMainInfo.getCaseQrCodeUrl());
            result.put("caseBarCodeUrl", caseMainInfo.getCaseBarCodeUrl());
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("生成行政行为码异常", e);
        }
        return null;
    }


    /**
     * 描述：生成缴款二维码简易处罚文书
     *
     * @author shishengyao
     * @date 2022/09/26
     */
    public void getPaymentQRCodeDocument(String caseId) {
        //简易处罚,查询缴款方式
        CaseMainDetailSimpleInfo simpleInfo = caseMainDetailSimpleInfoService.getCaseMainDetailSimpleInfo(caseId);
        if (PayWayEnum.OFF_SITE.getCode().equals(simpleInfo.getPayWay()) && simpleInfo.getPunishKinds().contains("罚款")) {
            //查询简易处罚文书列表
            CaseDocumentRecordDto caseDocumentRecord = caseDocumentRecordMapper.selectCaseDocumentRecordByKindCode(caseId, Constant.STRING_KIND_CODE_JYCXCFJDS);
            //未签字确认，生成缴费单
            if (ObjectUtil.isNotEmpty(caseDocumentRecord) && ObjectUtil.isEmpty(caseDocumentRecord.getDocumentUrlAfterSign())) {
                JSONObject jsonObject = JSON.parseObject(caseDocumentRecord.getDocumentContent());
                // 生成并获取缴费单号
                CasePaymentSlipNumberSaveDto slipNumberSaveDto = new CasePaymentSlipNumberSaveDto();
                slipNumberSaveDto.setCaseId(caseDocumentRecord.getCaseId());
                slipNumberSaveDto.setDocumentCatalogCode(caseDocumentRecord.getDocumentCatalogCode());
                slipNumberSaveDto.setCaseType(CaseTypeEnum.SIMPLE_PROCEDURE.getCode());
                slipNumberSaveDto.setPartyId(caseDocumentRecord.getPartyId());
                Result result = PunishMainClientUtil.httpPost(PunishMainServicePortUriConstant.SAVE_CASE_PAYMENT_MAIN_RECORD, slipNumberSaveDto);
                Map<String, Object> record = JSONObject.parseObject(result.getData().toString(), Map.class);
                jsonObject.put("qrBase64", record.get("qrBase64"));
                // 重新生成文书
                FillAndConvertToPdfRequest pdfRequest = new FillAndConvertToPdfRequest();
                HashMap<String, Object> jsonMap = new HashMap<>(64);
                for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
                    jsonMap.put(entry.getKey(), entry.getValue());
                }
                pdfRequest.setTemplateCode(caseDocumentRecord.getDocumentTemplateCode());
                pdfRequest.setParamMap(jsonMap);
                Map<String, String> unSealPdfUrl = appCaseBeforeDocumentRecordService.getConvertedPdfUrl(pdfRequest);
                ConfigBusiParamDocumentInfo detailByDocumentCatalogCode = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(caseDocumentRecord.getDocumentCatalogCode());
                //判断是否需要签章
                String pdfSealUrl = "";
                if (YesOrNoEnum.YES.getCode().equals(detailByDocumentCatalogCode.getIsDeptSign())) {
                    CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(caseDocumentRecord.getCaseId());
                    // 签字捺印
                    FileSealInfoQueryDto queryDto = new FileSealInfoQueryDto();
                    SysDepartParam sysDepartParam = sysDepartParamService.getSysDepartParamByOrgCodeAndDeptCode(caseMainInfo.getCaseOrgCode(), caseMainInfo.getCaseDeptCode());
                    queryDto.setUniscid(sysDepartParam.getUnicode());
                    queryDto.setFileBase64(unSealPdfUrl.get("fileBase64"));
                    queryDto.setDeptCode(caseMainInfo.getCaseDeptCode());
                    pdfSealUrl = appCaseBeforeDocumentRecordService.dealFileSeal(queryDto);
                }
                // 返回
                Map<String, Object> resultMap = new HashMap<>(16);
                resultMap.put("success", "true");
                resultMap.put("pdfSealUrl", pdfSealUrl);
                caseDocumentRecord.setDocumentUrlAfterSeal(pdfSealUrl);
                caseDocumentRecord.setDocumentContent(jsonObject.toJSONString());
                caseDocumentRecordMapper.updateByPrimaryKeySelective(caseDocumentRecord);
            }

        }
    }

    /**
     * 描述： 检验姓名与身份证是否匹配
     *
     * @return {@link boolean}
     * @author: zhengqiang
     * @date: 2022/10/11
     * @param: realName
     * @param: idCard
     **/
    @Override
    public boolean checkRealName(String realName, String idCard) {
        boolean flag = true;
        RealNameCheckDto checkDto = new RealNameCheckDto();
        checkDto.setIdCard(idCard);
        checkDto.setRealName(realName);
        try {
            Result<JSONObject> result = PunishMainClientUtil.httpPost(PunishMainServicePortUriConstant.CHECK_REAL_NAME, checkDto);
            if (!ObjectUtils.isEmpty(result) && HttpStatus.HTTP_OK == result.getCode()) {
                RealNameCheckVo realNameCheckVo = JSONObject.parseObject(result.getData().toJSONString(), RealNameCheckVo.class);
                if (RealNameCheckResultEnum.CHECK_DIFFERENT.getCode().equals(realNameCheckVo.getRealNameCheckResultCode())) {
                    flag = false;
                }
            }
        } catch (Exception e) {
            log.error("调用实名认证接口异常,idCard:{},异常原因: {}", idCard, e);
        }
        return flag;
    }


}
